1########################################################################
2##
3## Copyright (C) 1993-2021 The Octave Project Developers
4##
5## See the file COPYRIGHT.md in the top-level directory of this
6## distribution or <https://octave.org/copyright/>.
7##
8## This file is part of Octave.
9##
10## Octave is free software: you can redistribute it and/or modify it
11## under the terms of the GNU General Public License as published by
12## the Free Software Foundation, either version 3 of the License, or
13## (at your option) any later version.
14##
15## Octave is distributed in the hope that it will be useful, but
16## WITHOUT ANY WARRANTY; without even the implied warranty of
17## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18## GNU General Public License for more details.
19##
20## You should have received a copy of the GNU General Public License
21## along with Octave; see the file COPYING.  If not, see
22## <https://www.gnu.org/licenses/>.
23##
24########################################################################
25
26## -*- texinfo -*-
27## @deftypefn  {} {} list_primes ()
28## @deftypefnx {} {} list_primes (@var{n})
29## List the first @var{n} primes.
30##
31## If @var{n} is unspecified, the first 25 primes are listed.
32## @seealso{primes, isprime}
33## @end deftypefn
34
35function retval = list_primes (n = 25)
36
37  if (nargin > 1)
38    print_usage ();
39  elseif (! isreal (n) || ! isscalar (n))
40    error ("list_primes: N must be a real scalar");
41  endif
42
43  n = floor (n);
44
45  if (n < 1)
46    retval = [];
47    return;
48  elseif (n == 1)
49    retval = 2;
50    return;
51  endif
52
53  list = primes (n * log (5 * n));
54  if (numel (list) < n)
55    ## Algorithm tested up to n=10,000 without failure.
56    error ("list_primes: Algorithm failed.  Try primes (n*log (6*n))(1:n)");
57  endif
58
59  retval = list(1:n);
60
61endfunction
62
63
64%!assert (list_primes (), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, ...
65%!                         43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])
66%!assert (list_primes (5), [2, 3, 5, 7, 11])
67
68%!assert (list_primes (0), [])
69%!assert (list_primes (1), [2])
70
71## Test input validation
72%!error list_primes (1, 2)
73%!error <N must be a real scalar> list_primes (i)
74%!error <N must be a real scalar> list_primes ([1 2])
75