7017
|
1 ## Copyright (C) 1993, 1995, 1996, 1997, 2000, 2002, 2005, 2007 |
|
2 ## John W. Eaton |
2313
|
3 ## |
|
4 ## This file is part of Octave. |
|
5 ## |
|
6 ## Octave is free software; you can redistribute it and/or modify it |
|
7 ## under the terms of the GNU General Public License as published by |
7016
|
8 ## the Free Software Foundation; either version 3 of the License, or (at |
|
9 ## your option) any later version. |
2313
|
10 ## |
|
11 ## Octave is distributed in the hope that it will be useful, but |
|
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
14 ## General Public License for more details. |
|
15 ## |
|
16 ## You should have received a copy of the GNU General Public License |
7016
|
17 ## along with Octave; see the file COPYING. If not, see |
|
18 ## <http://www.gnu.org/licenses/>. |
245
|
19 |
3449
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {} list_primes (@var{n}) |
|
22 ## List the first @var{n} primes. If @var{n} is unspecified, the first |
|
23 ## 30 primes are listed. |
2311
|
24 ## |
3449
|
25 ## The algorithm used is from page 218 of the |
|
26 ## @iftex |
|
27 ## @tex |
6248
|
28 ## {\TeX}book. |
3449
|
29 ## @end tex |
|
30 ## @end iftex |
|
31 ## @ifinfo |
|
32 ## TeXbook. |
|
33 ## @end ifinfo |
|
34 ## @end deftypefn |
68
|
35 |
2314
|
36 ## Author: jwe |
|
37 |
2311
|
38 function retval = list_primes (n) |
68
|
39 |
|
40 if (nargin > 0) |
4030
|
41 if (! isscalar (n)) |
68
|
42 error ("list_primes: argument must be a scalar"); |
|
43 endif |
|
44 endif |
|
45 |
|
46 if (nargin == 0) |
|
47 n = 30; |
|
48 endif |
|
49 |
|
50 if (n == 1) |
|
51 retval = 2; |
|
52 return; |
|
53 endif |
|
54 |
|
55 if (n == 2) |
|
56 retval = [2; 3]; |
|
57 return; |
|
58 endif |
|
59 |
|
60 retval = zeros (1, n); |
|
61 retval (1) = 2; |
|
62 retval (2) = 3; |
|
63 |
|
64 n = n - 2; |
|
65 i = 3; |
|
66 p = 5; |
|
67 while (n > 0) |
|
68 |
|
69 is_prime = 1; |
|
70 is_unknown = 1; |
|
71 d = 3; |
|
72 while (is_unknown) |
|
73 a = fix (p / d); |
|
74 if (a <= d) |
|
75 is_unknown = 0; |
|
76 endif |
|
77 if (a * d == p) |
|
78 is_prime = 0; |
|
79 is_unknown = 0; |
|
80 endif |
|
81 d = d + 2; |
|
82 endwhile |
|
83 |
|
84 if (is_prime) |
|
85 retval (i++) = p; |
|
86 n--; |
|
87 endif |
|
88 p = p + 2; |
|
89 |
|
90 endwhile |
|
91 |
2326
|
92 endfunction |