home *** CD-ROM | disk | FTP | other *** search
/ Gold Fish 3 / goldfish_volume_3.bin / files / dev / c / cweb / examples / primes.w < prev    next >
Encoding:
Text File  |  1994-11-09  |  20.4 KB  |  463 lines

  1. % PRIMES example of WEB/CWEB portability.  This documentation was
  2. % originally published in the article ``Literate Programming'' by Donald
  3. % E. Knuth in ``The Computer Journal'', May 1984, and later in the book
  4. % ``Literate Programming'', October 1991, where it appeared as the first
  5. % example of WEB programming for Pascal.  It has been translated into
  6. % CWEB by Andreas Scherer to show the ease of portability between
  7. % Pascal/WEB and C/CWEB.  As little changes as possible were made, so that
  8. % the section numbering of the Pascal and the C version are identical,
  9. % except that a small list of related literature was appended at the end.
  10. % Minor changes to include extra C functionality are mentioned in the text
  11. % that follows.  The `cite' feature of CWEB 2.8 is used.
  12.  
  13. % This program is distributed WITHOUT ANY WARRANTY, express or implied.
  14. % WEB Version --- Don Knuth, 1986
  15. % CWEB Version --- Andreas Scherer, 1993
  16.  
  17. \font\csc=cmcsc10
  18. \def\PASCAL/{{\csc Pascal\spacefactor1000}}
  19. \def\[{\ifhmode\ \fi$[\mkern-2mu[$}
  20. \def\]{$]\mkern-2mu]$\ }
  21. \def\Section{\mathhexbox278}
  22. \hyphenation{Dijk-stra}
  23.  
  24. \def\title{PRIMES (C Version 1.1)}
  25. \def\topofcontents{\null\vfill
  26.   \centerline{\titlefont Printing prime numbers}
  27.   \vskip15pt
  28.   \centerline{(C Version 1.1)}
  29.   \vfill}
  30.  
  31. @* Printing primes: An example of {\tt CWEB}. The following program is
  32. essentially the same as Edsger Dijkstra's@^Dijkstra, Edsger@> ``first
  33. example of step-wise program composition,'' found on pages 26--39 of his
  34. {\sl Notes on Structured Programming\/} [1], as presented by Donald E.
  35. Knuth@^Knuth, Donald E.@> on pages 103--112 of his {\sl Literate
  36. Programming\/} [2], but it has been translated into the \.{CWEB} language
  37. by Andreas Scherer@^Scherer, Andreas@>.
  38. @.CWEB@>@.WEB@>
  39.  
  40. \[Double brackets will be used in what follows to enclose comments relating
  41. to \.{CWEB} itself, because the chief purpose of this program is to introduce
  42. the reader to the \.{CWEB} style of documentation. \.{CWEB} programs are always
  43. broken into small sections, each of which has a serial number; the present
  44. section is number 1.\]
  45.  
  46. Dijkstra's program prints a table of the first thousand prime numbers. We
  47. shall begin as he did, by reducing the entire program to its top-level
  48. description. \[Every section in a \.{CWEB} program begins with optional {\it
  49. commentary\/} about that section, and ends with optional {\it program
  50. text\/} for the section. For example, you are now reading part of the
  51. commentary in \Section1, and the program text for \Section1 immediately
  52. follows the present paragraph. Program texts are specifications of \CEE/ 
  53. programs; they either use \CEE/ language directly, or they use angle brackets
  54. to represent \CEE/ code that appears in other sections. For example, the
  55. angle-bracket notation `|@<Program to print...@>|' is \.{CWEB}'s way of saying
  56. the following: ``The \CEE/ text to be inserted here is called `Program to
  57. print $\ldots$ numbers', and you can find out all about it by looking at
  58. section 2.'' One of the main characteristics of \.{CWEB} is that different
  59. parts of the program are usually abbreviated, by giving them such an
  60. informal top-level description.\]
  61.  
  62. @c
  63. @<Program to print the first thousand prime numbers@>
  64.  
  65. @ This program has no input, because we want to keep it rather simple. The
  66. result of the program will be to produce a list of the first thousand prime
  67. numbers, and this list will appear on the |stdout| file.
  68.  
  69. Since there is no input, we declare the value |MM==1000| as a compile-time
  70. constant. The program itself is capable of generating the first |MM| prime
  71. numbers for any positive |MM|, as long as the computer's finite limitations
  72. are not exceeded. The boolean values |TRUE| and |FALSE| are defined.
  73.  
  74. \[The program text below specifies the ``expanded meaning'' of `|@<Program
  75. to print...@>|'; notice that it involves the top-level descriptions of two
  76. other sections. When those top-level descriptions are replaced by their
  77. expanded meanings, a syntactically correct \CEE/ program will be obtained.\]
  78.  
  79. @d MM    1000
  80. @d TRUE     1
  81. @d FALSE    0
  82.  
  83. @<Program to print...@>=
  84. #include <stdio.h>
  85.  
  86. void main(void)
  87.    {
  88.    @<Variables of the program@>@;@#
  89.  
  90.    @<Print the first |MM| prime numbers@>@;
  91.    }
  92.  
  93. @* Plan of the program. We shall proceed to fill out the rest of the
  94. program by making whatever decisions seem easiest at each step; the idea
  95. will be to strive for simplicity first and efficiency later, in order to
  96. see where this leads us. The final program may not be optimum, but we want
  97. it to be reliable, well motivated, and reasonably fast.
  98.  
  99. Let us decide at this point to maintain a table that includes all of the
  100. prime numbers that will be generated, and to separate the generation
  101. problem from the printing problem.
  102.  
  103. \[The \.{CWEB} description you are reading once again follows a pattern that
  104. will soon be familiar: A typical section begins with comments and ends with
  105. program text. The comments motivate and explain noteworthy features of the
  106. program text.\]
  107.  
  108. @<Print the first...@>=
  109.    @<Fill table |p| with the first |MM| prime numbers@>@;
  110.    @<Print table |p|                                 @>@;
  111.  
  112. @ How should table |p| be represented? Two possibilities suggest
  113. themselves: We could construct a sufficiently large array of boolean values
  114. in which the |k|th entry is |TRUE| if and only if the number |k| is prime;
  115. or we could build an array of integers in which the |k|th entry is the
  116. |k|th prime number. Let us choose the latter alternative, by introducing an
  117. integer array called |p[MM]|.
  118.  
  119. In the documentation below, the notation `|p[k]|' will refer to the |k|th
  120. element of array |p|, while `$p_k$' will refer to the |k|th prime number.
  121. If the program is correct, |p[k-1]| will either be equal to $p_k$ or it
  122. will not yet have been assigned any value. (Note that arrays in \CEE/ are
  123. indexed starting from 0 and not from 1 as in \PASCAL/)
  124. @^Differences between \PASCAL/ and \CEE/@>
  125.  
  126. \[Incidentally, our program will eventually make use of several more
  127. variables as we refine the data structures. All of the sections where
  128. variables are declared will be called `|@<Variables of...@>|'; the
  129. number `4' in this name refers to the present section, which is the first
  130. section to specify the expanded meaning of `|@<Variables of...@>|'.
  131. The note `{\eightrm See also~$\ldots$}' refers to all of the other sections
  132. that have the same top-level description. The expanded meaning of
  133. `|@<Variables of...@>|' consists of all the program texts for this name,
  134. not just the text found in \Section4.\]
  135.  
  136. @<Variables of the program@>=
  137.    int p[MM]; /* the first |MM| prime numbers, in increasing order */
  138.  
  139. @* The output phase. Let's work on the second part of the program first.
  140. It's not as interesting as the problem of computing prime numbers; but the
  141. job of printing must be done sooner or later, and we might as well do it
  142. sooner, since it will be good to have it done. \[And it is easier to learn
  143. \.{CWEB} when reading a program that has comparatively few distracting
  144. complications.\]
  145.  
  146. Since |p| is simply an array of integers, there is little difficulty in
  147. printing the output, except that we need to decide upon a suitable output
  148. format. Let us print the table on separate pages, with |RR| rows and |CC|
  149. columns per page, where every column is |WW| character positions wide. In
  150. this case we shall choose |RR==50|, |CC==5|, and |WW==10|, so that
  151. the first 1000~primes will appear on four pages. The program will not assume
  152. that |MM| is an exact multiple of |RR@t${}\times{}$@>CC|.
  153. @^output format@>
  154. @^Differences between \PASCAL/ and \CEE/@>
  155.  
  156. @d RR 50 /* this many rows will be on each page in the output         */
  157. @d CC  5 /* this many columns will be on each page in the output      */
  158. @d WW 10 /* this many character positions will be used in each column */
  159.  
  160. @ In order to keep this program reasonably free of notations that are
  161. uniquely \CEE/esque, \[and in order to illustrate more of the facilities of
  162. \.{CWEB},\] a few macro definitions for low-level output instructions are
  163. introduced here. All of the output-oriented commands in the remainder of
  164. the program will be stated in terms of five simple primitives called
  165. |print_string|, |print_integer|, |print_entry|, |new_line|, and |new_page|.
  166.  
  167. \[Sections of a \.{CWEB} program are allowed to contain {\it macro
  168. definitions} between the opening comments and the closing program text. The
  169. general format for each section is actually tripartite: commentary, then
  170. definitions, then program. Any of the three parts may be absent; for
  171. example, the present section contains no program text.\]
  172.  
  173. \[Simple macros simply substitute a bit of \CEE/ code for an identifier.
  174. Parametric macros are similar, but they also substitute an argument
  175. wherever `A' occurs in the macro definition. (You may \#|define| macros with
  176. more than just one parameter in \CEE/.) The first three macro definitions
  177. here are parametric; the other two are simple. (I am using |fputs| in order
  178. to get rid of the surplus `new line' character inserted by |puts|, and I am
  179. using |putc| instead of |putchar| for consistency in notation.)\]
  180. @^Differences between \PASCAL/ and \CEE/@>
  181.  
  182. @d print_string(A)
  183.    fputs(A,stdout) /* put a given string into the |stdout| file */
  184. @d print_integer(A)
  185.    printf("%d",A) /* put a given integer into the |stdout| file, in decimal
  186.    notation, using only as many digit positions as necessary */
  187. @d print_entry(A)
  188.    printf("%*d",WW,A) /* like |print_integer|, but |WW| character positions
  189.    are filled, inserting blanks at the left */
  190. @d new_line putc('\n',stdout); fflush(stdout)
  191.    /* advance to a new line in the |stdout| file */
  192. @d new_page putc('\f',stdout); fflush(stdout)
  193.    /* advance to a new page in the |stdout| file */
  194.  
  195. @ Several variables are needed to govern the output process. When we begin
  196. to print a new page, the variable |page_number| will be the ordinal number
  197. of that page, and |page_offset| will be such that |p[page_offset-1]| is the
  198. first prime to be printed. Similarly, |p[row_offset-1]| will be the first
  199. prime in a given row.
  200.  
  201. \[Notice the notation `$\mathrel+\E$' below; this indicates that the present
  202. section has the same name as a previous section, so the program text will
  203. be appended to some text that was previously specified.\]
  204.  
  205. @<Variables of the program@>=
  206.    int page_number;
  207.       /* one more than the number of pages printed so far */
  208.    int page_offset;
  209.       /* index into |p| for the first entry on the current page */
  210.    int row_offset;
  211.       /* index into |p| for the first entry in the current row */
  212.    int c;
  213.       /* runs through the columns in a row (|0@t${}\ldots{}$@>CC|) */
  214.  
  215. @ Now that appropriate auxiliary variables have been introduced, the
  216. process of outputting table |p| almost writes itself.
  217.  
  218. @<Print table |p|@>={
  219.    page_number = page_offset = 1;
  220.    while(page_offset <= MM) {
  221.       @<Output a page of answers@>@;
  222.       page_number++;
  223.       page_offset += RR*CC;
  224.       }
  225.    }
  226.  
  227. @ A simple heading is printed at the top of each page.
  228. @^output format@>
  229. @^page headings@>
  230. @<Output a page of answers@>={
  231.    print_string("The First ");@+               print_integer(MM);
  232.    print_string(" Prime Numbers --- Page ");@+ print_integer(page_number);
  233.    new_line;@+ new_line; /* there's a blank line after the heading */
  234.    for(row_offset = page_offset; row_offset <= page_offset + RR - 1;
  235.       row_offset++)
  236.       @<Output a line of answers@>@;
  237.    new_page;
  238.    }
  239.  
  240. @ The first row will contain
  241. $$
  242.   p[1-1],\thinspace p[1+\.{RR}-1],\thinspace
  243.   p[1+2\cdot\.{RR}-1],\thinspace \ldots;
  244. $$
  245. a similar pattern holds for each value of the |row_offset|.
  246.  
  247. @<Output a line of answers@>={
  248.    for(c=0; c<=CC-1; c++) {
  249.       if(row_offset+c*RR <= MM)
  250.          print_entry(p[row_offset + c*RR -1]);
  251.       }
  252.    new_line;
  253.    }
  254.  
  255. @* Generating the primes. The remaining task is to fill table |p| with the
  256. correct numbers. Let us do this by generating its entries one at a time:
  257. Assuming that we have computed all primes that are |j| or less, we will
  258. advance |j| to the next suitable value, and continue doing this until the
  259. table is completely full.
  260.  
  261. The program includes a provision to initialize the variables in certain
  262. data structures that will be introduced later.
  263.  
  264. @<Fill table |p| with...@>=
  265.    @<Initialize the data structures@>@;
  266.    while(k < MM) {
  267.       @<Increase |j| until it is the next prime number@>@;
  268.       k++;@+ p[k-1] = j;
  269.       }
  270.  
  271. @ We need to declare the two variables |j| and |k| that were just
  272. introduced.
  273.  
  274. @<Variables of the...@>=
  275.    int j; /* all primes ${}\leq j$ are in table |p|                    */
  276.    int k; /* this many primes are in table |p| (|0@t${}\ldots{}$@>MM|) */
  277.  
  278. @ So far we haven't needed to confront the issue of what a prime number is.
  279. But everything else has been taken care of, so we must delve into a bit of
  280. number theory now.
  281.  
  282. By definition, a number is called prime if it is an integer greater than 1
  283. that is not evenly divisible by any smaller prime number. Stating this
  284. another way, the integer $j>1$ is not prime if and only if there exists a
  285. prime number $p_n<j$ such that |j| is a multiple of $p_n$.
  286. @^prime number, definition of@>
  287.  
  288. Therefore the section of the program that is called `|@<Increase |j|...@>|'
  289. could be coded very simply: `|do { j++; @<Give to...@> } while(!j_prime)@;|'.
  290. And to compute the boolean value |j_prime|, the following would suffice:
  291. `|j_prime=TRUE; for(n=1; n<=k; n++) @<If |p[n-1]|...@>@;|'.
  292.  
  293. @ However, it is possible to obtain a much more efficient algorithm by
  294. using more facts of number theory. In the first place, we can speed things
  295. up a bit by recognizing that $p_1=2$ and that all subsequent primes are
  296. odd; therefore we can let |j| run through odd values only. Our Program now
  297. takes the following form:
  298.  
  299. @<Increase...@>=
  300.    do@+ {
  301.       j += 2;
  302.       @<Update variables that depend on |j|                 @>@;
  303.       @<Give to |j_prime| the meaning: |j| is a prime number@>@;
  304.       }@+ while(!j_prime);
  305.  
  306. @ The |do| loop in the previous section introduces a boolean variable
  307. |j_prime|, so that it will not be necessary to resort to a |goto|
  308. statement. (We are following Dijkstra~[1], not Knuth~[3].)
  309. @^Dijkstra, Edsger@>
  310. @^Knuth, Donald E.@>
  311.  
  312. @<Variables...@>=
  313.    unsigned char j_prime; /* is |j| a prime number? */
  314.  
  315. @ In order to make the odd-even trick work, we must of course initialize
  316. the variables |j|, |k|, and |p[0]| as follows.
  317.  
  318. @<Initialize...@>=
  319.    j = k = 1;@+ p[0] = 2;
  320.  
  321. @ Now we can apply more number theory in order to obtain further economies.
  322. If |j| is not prime, its smallest prime factor $p_n$ will be $\sqrt{j}$ or
  323. less. Thus if we know a number |ord| such that
  324. $$
  325.   p[ord-1]^2>j,
  326. $$
  327. and if |j| is odd, we need only test for divisors in the set
  328. $\{$|p[1]|$,\ldots,$|p[ord-2]|$\}$. This is much faster than testing
  329. divisibility by the full set $\{$|p[1]|$,\ldots,$|p[k-1]|$\}$, since |ord|
  330. tends to be much smaller than |k|. (Indeed, when |k| is large, the celebrated
  331. ``prime number theorem'' implies that the value of |ord| will be approximately
  332. $2\sqrt{k}/{\rm ln}k$.)
  333.  
  334. Let us therefore introduce |ord| into the data structure. A moment's
  335. thought makes it clear that |ord| changes in a simple way when |j|
  336. increases, and that another variable |square| facilitates the updating
  337. process.
  338.  
  339. @<Variables...@>=
  340.    int ord; /* the smallest index ${}\geq2$ such that $p^2_{ord}>j$ */
  341.    int square; /* |square|${}=p^2_{ord}$ */
  342.  
  343. @ @<Initialize...@>=
  344.    ord=2;@+ square=9;
  345.  
  346. @ The value of |ord| will never get larger than a certain value |ORD_MAX|,
  347. which must be chosen sufficiently large. It turns out that |ord| never
  348. exceeds 30 when |MM==1000|.
  349.  
  350. @d ORD_MAX 30 /* $p^2_{ord\_max}$ must exceed $p_M$ */
  351.  
  352. @ When |j| has been increased by 2, we must increase |ord| by unity when
  353. $j=p^2_{ord}$, i.e., when |j==square|.
  354.  
  355. @<Update variables that depend on |j|@>=
  356.    if(j==square) {
  357.       ord++;@+ @<Update variables that depend on |ord|@>@;
  358.       }
  359.  
  360. @ At this point in the program, |ord| has just been increased by unity, and
  361. we want to set |square@t${}=p^2_{ord}$@>|. A surprisingly subtle point arises
  362. here: How do we know that $p_{ord}$ has already been computed, i.e., that
  363. |ord<=k|? If there were a gap in the sequence of prime numbers, such
  364. that $p_{k+1}>p^2_k$ for some |k|, then this part of the program would refer to
  365. the yet-uncomputed value |p[k]| unless some special test were made.
  366.  
  367. Fortunately, there are no such gaps. But no simple proof of this fact is
  368. known. For example, Euclid's famous demonstration that there are infinitely
  369. many prime numbers is strong enough to prove only that $p_{k+1}\leq
  370. p_1\ldots p_k+1$. Advanced books on number theory come to our rescue by
  371. showing that much more is true; for example, ``Bertrand's postulate''
  372. states that $p_{k+1}<2p_k$ for all $k$.
  373. @^Bertrand, Joseph, postulate@>
  374. @^Euclid@>
  375.  
  376. @<Update variables that depend on |ord|@>=
  377.    square = p[ord-1]*p[ord-1]; /* at this point |ord<=k| */
  378.  
  379. @* The inner loop. Our remaining task is to determine whether or not a
  380. given integer |j| is prime. The general outline of this part of the program
  381. is quite simple, using the value of |ord| as described above.
  382.  
  383. @<Give to...@>=
  384.    n = 2;@+ j_prime = TRUE;
  385.    while((n<ord) && j_prime) {
  386.       @<If |p[n-1]| is a factor of |j|, set |j_prime=FALSE|@>@;
  387.       n++;
  388.       }
  389.  
  390. @ @<Variables...@>=
  391.    int n; /* runs from 2 to |ord| when testing divisibility */
  392.  
  393. @ Let's suppose that division is very slow or nonexistent on our machine.
  394. We want to detect nonprime odd numbers, which are odd multiples of the set
  395. of primes $\{p_2,\ldots,p_{ord-1}\}$.
  396.  
  397. Since |ORD_MAX| is small, it is reasonable to maintain an auxiliary table
  398. of the smallest odd multiples that haven't already been used to show that
  399. some |j| is nonprime. In other words, our goal is to ``knock out'' all of
  400. the odd multiples of each $p_n$ in the set $\{p_2,\ldots,p_{ord-1}\}$, and
  401. one way to do this is to introduce an auxiliary table that serves as a
  402. control structure for a set of knock-out procedures that are being
  403. simulated in parallel. (The so-called ``sieve of Eratosthenes'' generates
  404. primes by a similar method, but it knocks out the multiples of each prime
  405. serially.)
  406. @^Eratosthenes, sieve of@>
  407.  
  408. The auxiliary table suggested by these considerations is a |mult| array that
  409. satisfies the following invariant condition: For $2\leq n<ord$, |mult[n-1]|
  410. is an odd multiple of $p_n$ such that |mult[n-1]@t${}<j+2p_n$@>|.
  411.  
  412. @<Variables...@>=
  413.    int mult[ORD_MAX]; /* runs through multiples of primes */
  414.  
  415. @ When |ord| has been increased, we need to initialize a new element of the
  416. |mult| array. At this point |j==p[ord-2]@t$^2$@>|, so there is no need for an
  417. elaborate computation.
  418.  
  419. @<Update variables that depend on |ord|@>=
  420.    mult[ord-2]=j;
  421.  
  422. @ The remaining task is straightforward, given the data structures already
  423. prepared. Let us recapitulate the current situation: The goal is to test
  424. whether or not |j| is divisible by $p_n$, without actually performing a
  425. division. We know that |j| is odd, and that |mult[n-1]| is an odd multiple
  426. of $p_n$ such that |mult[n-1]<j+2@t$p_n$@>|. If |mult[n-1]<j|, we can
  427. increase |mult[n-1]| by $2p_n$ and the same conditions will hold. On the
  428. other hand if |mult[n-1]<=j|, the conditions imply that |j| is
  429. divisible by $p_n$ if and only if |j==mult[n-1]|.
  430.  
  431. @<If |p[n-1]|...@>=
  432.    while(mult[n-1]<j)
  433.       mult[n-1] += p[n-1]+p[n-1];
  434.    if(mult[n-1]==j)
  435.       j_prime=FALSE;
  436.  
  437. @* For further reading. Here is a very short list of literature that has
  438. been mentioned in this text. A full reference can be found in [2].
  439. {\frenchspacing\parindent=1cm
  440. \bigskip
  441. \item{[1]} Ole-Johan Dahl, Edsger W. Dijkstra, and C. A. R. Hoare, {\sl
  442. Structured programming\/} (London: Academic Press, 1972), 220 pp.
  443. \item{[2]} Donald E. Knuth, {\sl Literate Programming\/} (Leland Stanford
  444. Junior University, 1992), 368 pp.
  445. \item{[3]} Donald E. Knuth, ``Structured programming with {\bf go to}
  446. statements,'' {\sl Computing Surveys\/} {\bf 6}, 4 (December 1974),
  447. 261--301. (Reprinted as chapter 2 of [2])\par}
  448.  
  449. @* Index. Every identifier used in this program is shown here together with
  450. a list of the section numbers where that identifier appears. The section
  451. number is underlined if the identifier was defined in that section.
  452. However, one-letter identifiers are indexed only at their point of
  453. definition, since such identifiers tend to appear almost everywhere. \[An
  454. index like this is prepared automatically by the \.{CWEB} software, and it is
  455. appended to the final section of the program.\]
  456.  
  457. This index also refers to some of the places where key elements of the
  458. program are treated. For example, the entries for `output format' and `page
  459. headings' indicate where details of the output format are discussed.
  460. Several other topics that appear in the documentation (e.g., `Bertrand's
  461. postulate') have also been indexed. \[Special instructions within a \.{CWEB}
  462. source file can be used to insert essentially anything into the index.\]
  463.