comparison scripts/specfun/isprime.m @ 5827:1fe78adb91bc

[project @ 2006-05-22 06:25:14 by jwe]
author jwe
date Mon, 22 May 2006 06:25:14 +0000
parents
children 93c65f2a5668
comparison
equal deleted inserted replaced
5826:6c6ff9b82577 5827:1fe78adb91bc
1 ## Copyright (C) 2000 Paul Kienzle
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
7 ## the Free Software Foundation; either version 2, or (at your option)
8 ## any later version.
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
16 ## along with Octave; see the file COPYING. If not, write to the Free
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 ## 02110-1301, USA.
19
20 ## -*- texinfo -*-
21 ## @deftypefn {Function File} {} isprime (@var{n})
22 ##
23 ## Return true if @var{n} is a prime number, false otherwise.
24 ##
25 ## Something like the following is much faster if you need to test a lot
26 ## of small numbers:
27 ##
28 ## @example
29 ## @var{t} = ismember (@var{n}, primes (max (@var{n} (:))));
30 ## @end example
31 ##
32 ## If max(n) is very large, then you should be using special purpose
33 ## factorization code.
34 ##
35 ## @seealso{primes, factor, gcd, lcm}
36 ## @end deftypefn
37
38 function t = isprime (n)
39 if (! isscalar (n))
40 nel = numel (n);
41 t = n;
42 for i = 1:nel
43 t(i) = isprime (t(i));
44 endfor
45 elseif (n != fix (n) || n < 2)
46 t = 0;
47 elseif (n < 9)
48 t = all (n != [4, 6, 8]);
49 else
50 q = n./[2, 3:2:sqrt(n)];
51 t = all (q != fix (q));
52 endif
53 endfunction