home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21eb.zip / octave / SCRIPTS.ZIP / scripts / miscellaneous / list_primes.m < prev    next >
Text File  |  1998-11-10  |  2KB  |  84 lines

  1. ## Copyright (C) 1996, 1997 John W. Eaton
  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, 59 Temple Place - Suite 330, Boston, MA
  18. ## 02111-1307, USA.
  19.  
  20. ## usage: list_primes (n)
  21. ##
  22. ## List the first n primes.  If n is unspecified, the first 30 primes
  23. ## are listed.
  24. ##
  25. ## The algorithm used is from page 218 of the TeXbook.
  26.  
  27. ## Author: jwe
  28.  
  29. function retval = list_primes (n)
  30.  
  31.   if (nargin > 0)
  32.     if (! is_scalar (n))
  33.       error ("list_primes: argument must be a scalar");
  34.     endif
  35.   endif
  36.  
  37.   if (nargin == 0)
  38.     n = 30;
  39.   endif
  40.  
  41.   if (n == 1)
  42.     retval = 2;
  43.     return;
  44.   endif
  45.  
  46.   if (n == 2)
  47.     retval = [2; 3];
  48.     return;
  49.   endif
  50.  
  51.   retval = zeros (1, n);
  52.   retval (1) = 2;
  53.   retval (2) = 3;
  54.  
  55.   n = n - 2;
  56.   i = 3;
  57.   p = 5;
  58.   while (n > 0)
  59.  
  60.     is_prime = 1;
  61.     is_unknown = 1;
  62.     d = 3;
  63.     while (is_unknown)
  64.       a = fix (p / d);
  65.       if (a <= d)
  66.         is_unknown = 0;
  67.       endif
  68.       if (a * d == p)
  69.         is_prime = 0;
  70.         is_unknown = 0;
  71.       endif
  72.       d = d + 2;
  73.     endwhile
  74.  
  75.     if (is_prime)
  76.       retval (i++) = p;
  77.       n--;
  78.     endif
  79.     p = p + 2;
  80.  
  81.   endwhile
  82.  
  83. endfunction
  84.