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