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