2303
|
1 ### Copyright (C) 1996 John W. Eaton |
|
2 ### |
|
3 ### This file is part of Octave. |
|
4 ### |
|
5 ### Octave is free software; you can redistribute it and/or modify it |
|
6 ### under the terms of the GNU General Public License as published by |
|
7 ### the Free Software Foundation; either version 2, or (at your option) |
|
8 ### any later version. |
|
9 ### |
|
10 ### Octave is distributed in the hope that it will be useful, but |
|
11 ### WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ### General Public License for more details. |
|
14 ### |
|
15 ### You should have received a copy of the GNU General Public License |
|
16 ### along with Octave; see the file COPYING. If not, write to the Free |
|
17 ### Software Foundation, 59 Temple Place - Suite 330, Boston, MA |
|
18 ### 02111-1307, USA. |
245
|
19 |
68
|
20 function retval = list_primes (n) |
|
21 |
2303
|
22 ## usage: list_primes (n) |
|
23 ## |
|
24 ## List the first n primes. If n is unspecified, the first 30 primes |
|
25 ## are listed. |
|
26 ## |
|
27 ## The algorithm used is from page 218 of the TeXbook. |
68
|
28 |
|
29 if (nargin > 0) |
|
30 if (! is_scalar (n)) |
|
31 error ("list_primes: argument must be a scalar"); |
|
32 endif |
|
33 endif |
|
34 |
|
35 if (nargin == 0) |
|
36 n = 30; |
|
37 endif |
|
38 |
|
39 if (n == 1) |
|
40 retval = 2; |
|
41 return; |
|
42 endif |
|
43 |
|
44 if (n == 2) |
|
45 retval = [2; 3]; |
|
46 return; |
|
47 endif |
|
48 |
|
49 retval = zeros (1, n); |
|
50 retval (1) = 2; |
|
51 retval (2) = 3; |
|
52 |
|
53 n = n - 2; |
|
54 i = 3; |
|
55 p = 5; |
|
56 while (n > 0) |
|
57 |
|
58 is_prime = 1; |
|
59 is_unknown = 1; |
|
60 d = 3; |
|
61 while (is_unknown) |
|
62 a = fix (p / d); |
|
63 if (a <= d) |
|
64 is_unknown = 0; |
|
65 endif |
|
66 if (a * d == p) |
|
67 is_prime = 0; |
|
68 is_unknown = 0; |
|
69 endif |
|
70 d = d + 2; |
|
71 endwhile |
|
72 |
|
73 if (is_prime) |
|
74 retval (i++) = p; |
|
75 n--; |
|
76 endif |
|
77 p = p + 2; |
|
78 |
|
79 endwhile |
|
80 |
|
81 endfunction |