1 ## Copyright (C) 2000-2012 Paul Kienzle
2 ## Copyright (C) 2010 VZLU Prague
4 ## This file is part of Octave.
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
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
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.
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>.
21 ## @deftypefn {Function File} {} isprime (@var{x})
22 ## Return a logical array which is true where the elements of @var{x} are
23 ## prime numbers and false where they are not.
25 ## If the maximum value in @var{x} is very large, then you should be using
26 ## special purpose factorization code.
31 ## @result{} [0, 1, 1, 0, 1, 0]
34 ## @seealso{primes, factor, gcd, lcm}
37 function t = isprime (x)
40 if (any ((x != floor (x) | x < 0)(:)))
41 error ("isprime: needs positive integers");
44 ## generate prime table of suitable length.
45 maxp = min (maxn, max (sqrt (maxn), 1e7)); # FIXME: threshold not optimized.
47 ## quick search for table matches.
48 t = lookup (pr, x, "b");
52 ## there are still possible primes. filter them out by division.
53 if (maxn <= intmax ("uint32"))
55 elseif (maxn <= intmax ("uint64"))
58 warning ("isprime: too large integers being tested");
60 pr = cast (pr(pr <= sqrt (maxn)), class (m));
62 m = m(rem (m, p) != 0);
63 if (length (m) < length (pr) / 10)
68 mm = arrayfun (@(x) all (rem (x, pr)), m);
71 m = cast (sort (m), class (x));
72 t |= lookup (m, x, "b");
83 %!assert (isprime (4), logical (0));
84 %!assert (isprime (3), logical (1));
85 %!assert (isprime (magic (3)), logical ([0, 0, 0; 1, 1, 1; 0, 0, 1]));
87 %!error isprime (1, 2)