home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cs.utexas.edu!asuvax!ncar!noao!amethyst!organpipe.uug.arizona.edu!news
- From: dave@cs.arizona.edu (Dave Schaumann)
- Newsgroups: comp.programming
- Subject: Re: how about PRIME numbers ?
- Message-ID: <1993Jan24.055343.2392@organpipe.uug.arizona.edu>
- Date: 24 Jan 93 05:53:43 GMT
- References: <peterd.727578786@tscc2>
- Sender: news@organpipe.uug.arizona.edu
- Reply-To: dave@cs.arizona.edu (Dave Schaumann)
- Organization: University of Arizona
- Lines: 53
- In-Reply-To: peterd@tscc2.macarthur.uws.edu.au
-
- In article <peterd.727578786@tscc2>, peterd@tscc2 writes:
- >Ok, I asked for an algorithm for PI (and got several responses - thank you)
- >
- >How about an efficent algorithm for PRIME numbers ?
-
- Well, for generating lists of 'em, there's always the Sieve of
- Erasthonese (sp?). Not especially fast, but you really only need
- to run it once...
-
- For testing primality (or prime factoring), here's a fairly obvious
- algorithm I came up with a long time ago:
-
-
- int is_prime( unsigned long n ) {
-
- unsigned long i, max = sqrt(n) ;
-
- if( n <= 3 ) return 1 ;
-
- if( n % 2 == 0 || n % 3 == 0 ) return 0 ;
- for( i = 6 ; i <= max+1 ; i += 6 )
- if( n % (i-1) == 0 || n % (i+1) == 0 ) return 0 ;
-
- return 1 ;
- }
-
- This works on two observations:
-
- 1. If a number is not prime, it must have a factor less than or
- equal to its square root.
-
- 2. Once you've checked for division by 2 and 3, there is a simple
- pattern for checking every 2 out of 6 possibilities thereafter
- (similar to the way once you check for division by 2, you only
- need to check for division by odd numbers)
-
- Theoretically, the second observation could be extended to include
- more prime factors. In practice, the pattern of candidate divisors
- is much more complicated (eg, for 5, the pattern length is 2*3*5=30
- numbers long), and the actual savings is increasingly small.
-
- On the other hand, this seems reasonably adequate. On a (lightly
- loaded) Sequent Symmetry, I used this algorithm to find the 194
- primes between 0xfffff000 and 0xffffffff (inclusive) in just over
- 20 seconds.
-
- I'm not sure that you can do better than this; I believe that there
- is at least one encryption method based on the fact that factoring
- very large numbers is highly time-consuming (ie, not practical beyond
- a certain point).
-
- --
- Dave Schaumann dave@cs.arizona.edu
-