home *** CD-ROM | disk | FTP | other *** search
- /*
- **
- ** Copyright (c) 1987, Robert L. McQueer
- ** All Rights Reserved
- **
- ** Permission granted for use, modification and redistribution of this
- ** software provided that no use is made for commercial gain without the
- ** written consent of the author, that all copyright notices remain intact,
- ** and that all changes are clearly documented. No warranty of any kind
- ** concerning any use which may be made of this software is offered or implied.
- **
- */
-
- /* return smallest prime >= i */
- int
- next_prime(int i)
- {
- if (i <= 2)
- return (2);
- if ((i%2) == 0)
- ++i;
- while (! is_prime(i))
- i += 2;
- return (i);
- }
-
- /*
- ** simply check all factors <= the square root of the number, with
- ** a minor wrinkle:
- **
- ** we split our checks into two separate chains which cover all
- ** numbers with no factors of 2 or 3, avoiding many of the non-
- ** prime factors. factor1 winds up being all integers = 5 mod 6,
- ** factor2 all integers >= 7 which = 1 mod 6. Anything = 0,2,3 or
- ** 4 mod 6 divides by 2 or 3.
- **
- ** this gives a rather small number of redundant factor checks for
- ** reasonable sized arguments (say < 10000). Only for extremely large
- ** numbers would the extra overhead justify a "smarter" algorithm.
- **
- ** only valid for i >= 2.
- */
- int
- is_prime(int i)
- {
- int factor1,factor2;
-
- if (i == 2 || i == 3)
- return(1);
-
- if ((i%3) == 0 || (i%2) == 0)
- return(0);
-
- factor1 = 5;
- factor2 = 7;
- while ((factor1 * factor1) <= i)
- {
- if ((i % factor1) == 0)
- return (0);
- if ((i % factor2) == 0)
- return (0);
- factor1 += 6;
- factor2 += 6;
- }
-
- return (1);
- }
-