7017
|
1 ## Copyright (C) 2000, 2006, 2007 Paul Kienzle |
5827
|
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 |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
5827
|
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 |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5827
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {} isprime (@var{n}) |
|
21 ## |
|
22 ## Return true if @var{n} is a prime number, false otherwise. |
|
23 ## |
|
24 ## Something like the following is much faster if you need to test a lot |
|
25 ## of small numbers: |
|
26 ## |
|
27 ## @example |
|
28 ## @var{t} = ismember (@var{n}, primes (max (@var{n} (:)))); |
|
29 ## @end example |
|
30 ## |
|
31 ## If max(n) is very large, then you should be using special purpose |
|
32 ## factorization code. |
|
33 ## |
|
34 ## @seealso{primes, factor, gcd, lcm} |
|
35 ## @end deftypefn |
|
36 |
|
37 function t = isprime (n) |
|
38 if (! isscalar (n)) |
|
39 nel = numel (n); |
|
40 t = n; |
|
41 for i = 1:nel |
|
42 t(i) = isprime (t(i)); |
|
43 endfor |
|
44 elseif (n != fix (n) || n < 2) |
|
45 t = 0; |
|
46 elseif (n < 9) |
|
47 t = all (n != [4, 6, 8]); |
|
48 else |
|
49 q = n./[2, 3:2:sqrt(n)]; |
|
50 t = all (q != fix (q)); |
|
51 endif |
|
52 endfunction |