Follow Slashdot stories on Twitter

 



Forgot your password?
typodupeerror
×
Programming Technology

Fun with Prime Numbers 472

Steve Litt writes "Fun With Prime Numbers contains a series of prime number finding algorithms starting with the most brute force imaginable, and working up to a paged algorithm capable of finding the first 1,716,050,469 primes in an hour and a half on a commodity machine. There are faster algorithms on the net, but these algorithms are within the reach of mere mortals and are fully explained."
This discussion has been archived. No new comments can be posted.

Fun with Prime Numbers

Comments Filter:
  • Obligatory (Score:5, Funny)

    by zedmelon ( 583487 ) on Tuesday November 09, 2004 @11:31PM (#10773357) Homepage Journal
    This article will be a prime target for bad jokes.
  • by TamMan2000 ( 578899 ) on Tuesday November 09, 2004 @11:32PM (#10773367) Journal
    I got a 404...
  • by Anonymous Coward on Tuesday November 09, 2004 @11:33PM (#10773373)
    Why not just save primes on a disk instead of recalculating them all the time?
    • by Anonymous Coward on Tuesday November 09, 2004 @11:48PM (#10773487)
      Why waste disk space with primes instead of just recalculating them?
    • by psetzer ( 714543 ) on Wednesday November 10, 2004 @12:01AM (#10773581)
      Actually, in the final implementation, I thought that he does that. It creates a few thousand files, each one containing n primes, and then it goes through each previous file up to the square root of the largest number in the current file, and then it quits and goes to the next file. If you want to duplicate this guy's efforts, I think that the biggest help for this would be a REALLY fast HD array and lots of RAM.
    • by Dasein ( 6110 ) <tedc@codebig. c o m> on Wednesday November 10, 2004 @01:31AM (#10774066) Homepage Journal
      There are a lot of them. [utm.edu]

      As a matter of fact 2048 bits can represent numbers up to 2^2048 ~= 3.23x10^616. By the Prime Number Theorem [wolfram.com] there is about 2.27x10^613 primes in that space. If each prime required 2048 bits to store, then storing all the 2048 bit primes requires more petabytes then you and I are likely to ever see.

      (Jeez I hope I didn't do the math wrong. The most convenient calc I have available to me as I write this in the Windows calc)
      • by maxwell demon ( 590494 ) on Wednesday November 10, 2004 @08:03AM (#10775225) Journal
        Indeed, the number of particles in the universe is assumed to be approximately 10^85, so if you would store one bit per particle, you'd need about 5*10^530 universes to store all those primes. Hell, even if you stored at every single particle as many bits as there are particles in the universe, you'd still need 5*10^445 universes.

        Of course that's assuming you stupidly write all those numbers individually down, using the whole 2048 bitf or each number. Now what if we compress the table?

        The complete list can, of course, be stored in a bitfield with 2^2048 individual bits which tell if a given number is prime or not (e.g. 1 means the number is prime, 0 means it's not). Now, of those 3.23*10^616 bits, about 2.27*10^613 bits are 1. So a simple approximation would be to treat the bits as independent, with each one having a probability of (2.27*10^613)/(3.23*10^616)=7.03*10^-4 of being 1. So if we neglect all correlations of the bits, we get an information of about 0.0084 bits per bitfield bit, which means we can compress to about 2.7*10^614 bits. That is, even neglecting all correlations (even the trivial ones of all even numbers except 2 being non-prime) we get only about 12 bits per prime. That's substantially less than the 2048 bits per prime we'd need with straightforward storage. Of course, we would still need an insane number of universes to store our table :-)

        Now, of course we know that we can "compress" the full table very well to a small prime-finding program which fits nicely on even a single floppy (but would take longer to "decompress" than we are willing to wait), so the list of primes doesn't actually contain too much information (indeed, the program can compress the whole infinite prime table - decompression of course needs unlimited ressources, then -, therefore the average information content of a single prime is obviously zero).
    • by Omniscient Ferret ( 4208 ) on Wednesday November 10, 2004 @04:03AM (#10774627)
      On my computer, generating primes from 2 to 2^32 takes a third of the time to unbzip2 the same list.
  • EVER!!!
  • by Dancin_Santa ( 265275 ) <DancinSanta@gmail.com> on Tuesday November 09, 2004 @11:35PM (#10773390) Journal
    I understand that number sequences like Fibonacci manifest themselves in Nature and others like pi provide a fairly decent random number generation method. However, aside from the interesting property that they can't be divided by anything other than themselves and 1, I do not 'get' what is interesting or useful about prime numbers.

    But then again, I haven't studied mathematics to any great extent beyond the multi-var calc and linear algebra back in high school. That was such a long time ago. Any math Geniuses out there want to clue is in on why primes are interesting?
  • I find that title so hard to appreciate, maybe I'm just not as big a geek as i thought.
  • Fun, prime numbers, in the same sentence without some means of not connecting them in a positve light?

    What manner of masochism is this page peddling in the name of fun?
  • by Anonymous Coward
    This sounds like one of those topics in high school where if you sounded interested you were written a raincheck for an after school beating by the rugby team.
  • Aren't most of the really large prime numbers only Mersenne primes?
    • Re:Mersenne (Score:3, Informative)

      by back_pages ( 600753 )
      Aren't most of the really large prime numbers only Mersenne primes?

      Rather, most of the Mersenne numbers are prime, and most of them are large. That doesn't begin to scratch the surface of most large prime numbers though.

      • Re:Mersenne (Score:3, Informative)

        by acidblood ( 247709 )
        Rather, most of the Mersenne numbers are prime


        Wrong. There's more than 1.5 million primes up to 24,036,583 (the largest Mersenne exponent known), and only 41 of these are Mersenne exponents.
        • Re:Mersenne (Score:3, Informative)

          by back_pages ( 600753 )
          Rather, most of the Mersenne numbers are prime

          Wrong. There's more than 1.5 million primes up to 24,036,583 (the largest Mersenne exponent known), and only 41 of these are Mersenne exponents.

          Read what I typed, then read what you typed.

          If I were wrong, then most of the Mersenne numbers would be composite. You have suggested that most of the large prime numbers are not Mersenne numbers, which is an unrelated concept, and substantiates my original post.

          • Re:Mersenne (Score:3, Informative)

            by acidblood ( 247709 )

            If I were wrong, then most of the Mersenne numbers would be composite.

            Do you have reading comprehension problems? Or is it just logic that escapes you? If only 41 primes up to 24,036,583 correspond to exponents of Mersenne primes, then the remaining 1.5 million or so primes up to 24,036,583 correspond to exponents of, you guessed it, Mersenne composites. I'd say that a compositeness ratio of 99.997% would indicate that `most' Mersenne numbers are composite.

            You have suggested that most of the large pri

    • No.
  • If this gets you really excited, you know you are the truest form of nerd.
    • Which is to say, I think this is really cool.
    • I wasn't all that excited, only because I wrote my own several years back. He did go a couple steps further and work around the memory problem with paging though, which I had never tried. I was limited by my ram.

      If I don't print or store the primes, I can find all the primes under 2 billion in 2 minutes on my 2.4ghz celeron, since after about 46k all it's doing is reading a bit array of what is and isn't prime. But adding a printf slows it down considerably.
  • Interesting code (Score:2, Interesting)

    by icekillis ( 777986 )
    Reminds me, here's code to generate prime numbers: (earlier thread)
    http://www.de.ioccc.org/2004/vik2.c

    to cheat: http://www.de.ioccc.org/2004/vik2.hint
    I didn't link them on purpose
  • by Anonymous Coward on Tuesday November 09, 2004 @11:39PM (#10773428)
    So the macros knock the time down from 4.49 to 4.15 seconds -- less than a 10% reduction. In my opinion, that's not enough benefit to give up the robustness and typechecking of functions.

    I never thought that I'd see a C programmer type something like that.
  • by xmas2003 ( 739875 ) on Tuesday November 09, 2004 @11:43PM (#10773456) Homepage
    While the prime number page is a bit odd (obligatory half-hearted pun), the author is Steve Litt who wrote Samba Unleashed ... plus there's already 40+ posts on the article, yet his web site is still pretty snappy despite the /. crowd ...

    BTW, the first bazillion prime numbers HAVE been calculated, so for those /.'ers with spare CPU cycles, consider something perhaps more worthwhile such as Folding@HOME [powder2glass.com]

  • Prime Resource (Score:2, Interesting)

    by d3m057h3n35 ( 695460 )
    Here's a nice, fun little resource for those interested in prime numbers. Actually, it's pretty large and exhaustive: The Prime Pages. [utm.edu] Make sure to check out Prime Curios! [utm.edu]; fascinating stuff.
  • by pestilence4hr ( 652767 ) on Tuesday November 09, 2004 @11:49PM (#10773499)
    A very fast segmented sieve (to find primes in an arbitrary range) can be found here [ieeta.pt], by Tomás Oliveira e Silva.

    Of tangential interest is his Goldbach conjecture verification project [ieeta.pt]. You can download his client and contribute to the project. He's shooting for 10^18...
  • superior algorithm (Score:2, Interesting)

    by Anonymous Coward
    djb:

    see http://cr.yp.to/primegen.html

    primegen is a small, fast library to generate prime numbers in order. It generates the 50847534 primes up to 1000000000 in just 8 seconds on a Pentium II-350; it prints them in decimal in just 35 seconds.
    primegen can generate primes up to 1000000000000000, although it is not optimized for primes past 32 bits. It uses the Sieve of Atkin instead of the traditional Sieve of Eratosthenes.

  • by 3770 ( 560838 ) on Tuesday November 09, 2004 @11:51PM (#10773514) Homepage
    There is a command in many unices and Linux called factor.

    If you want to be a true geek you can try it on your friends phone numbers and find out if it is a prime.

    Then, the next time you talk, inform them that their phone number is a prime, or tell them of their phone numbers prime factorization, and enjoy watching them think that you are a super geek and a super genius.

    For even better effect, pretend to count in your head before you tell them this.
  • ...it'll do those poor people stuck in the Cube [imdb.com].
  • Gaps between primes (Score:5, Interesting)

    by tbjw ( 760188 ) on Tuesday November 09, 2004 @11:55PM (#10773539)
    From the article:

    who can be sure that there aren't two consecutive primes somewhere that are more than 65536 apart

    Let's recall elementary number theory:

    65537! + 2 = 2 * 3 * ... * 65537 + 2 = 2 * (3 * ... * 65537 + 1)
    65537! + 3 = 2 * 3 * ... * 65537 + 3 = 3 * (2* 4 * ... * 65537 + 1)
    ...

    65537! + 65537 = 2* 3 * ... * 65536 * 65537 + 65537 = 65537(65536!+1)

    So the 65536 consecutive numbers 65537! +2 , ..., 65537! + 65537 are all nonprime (the first is divisible by 2, the second by 3, the thrid by 4 etc). Since we also know that there are infinitely many primes, there must be a prime greater than 65537! + 65537. The biggest prime less than 65537! + 2 and the least prime bigger than 65537! + 65537 are consecutive primes which are at least 65536 apart.

    Of course, 65537! is a massive number, which is unlikely to crop up in these calculations. There may be other sufficiently large gaps between primes among smaller numbers.
    Consider, for instance, the method above applied with 5 in the place of 65536. We see that {6! +2, ..., 6! + 5} ={722, 723, 724, 725, 726} are all nonprime, but also 24, 25, 26, 27, 28 are 5 consecutive nonprime numbers.
    For where we can expect large 'prime-free' gaps, I'll defer to any number theorist.
  • by gibs ( 827394 )
    Can someone tell me again what the point of this is?
  • 2^24036583-1 [mersenne.org], which contains over 7.2 million digits.

    The linked .txt file is 7.1 MB, so it probably will take a while. The Google cache [66.102.7.104] doesn't do the number justice. In fact, the cached number is divisible by 2...

  • by kuzb ( 724081 ) on Wednesday November 10, 2004 @12:02AM (#10773585)
    If you're interested in running a distributed.net-like application with the chance to make some money using your CPU cycles to help find prime numbers, have a look at here [mersenne.net]. They give some good information about what prime numbers are, and what they're good for.
  • by The Master Control P ( 655590 ) <ejkeeverNO@SPAMnerdshack.com> on Wednesday November 10, 2004 @12:09AM (#10773634)
    How about when you're on the vintage mainframe level in Tron 2.0, ask some random program to calculate the seventh even prime number. When he segfaults, you get access to the directory containing Tron Legacy. Just don't ask yourself that question...
  • by imag0 ( 605684 ) on Wednesday November 10, 2004 @12:15AM (#10773680) Homepage
    Now, who can forget the Prime Number Shitting Bear [surfeu.fi]?
  • Improvement (Score:4, Insightful)

    by acidblood ( 247709 ) <decio@@@decpp...net> on Wednesday November 10, 2004 @12:18AM (#10773700) Homepage
    Blockquoth the FA's author, regarding how to store a list of primes:

    Keeping it in an array is simplest, but one must declare the array before finding primes. How big do you declare it.

    Have a look here [utm.edu] for a pretty tight upper bound on the number of primes up to a given number. Using an array, instead of a linked list, would probably lead to a small speed improvement on his code.

    He could also use an std::vector from C++. As far as I can tell it's pretty easy to resize.
  • by Kenja ( 541830 ) on Wednesday November 10, 2004 @12:27AM (#10773752)
    "One is the loneliest number that you'll ever do Two can be as bad as one, its the loneliest number since the number one"
  • My Holloween Costume!

    I marked up a sweatshirt with a bunch of random prime numbers and, dum roll please, I WAS the 'Indivisible Man'.

    Tada.
    ~tel0p
  • take a class in abtract algebra, generally the first class in higher, proof-oriented mathematics. Primes have strong relevance in group theory (which is in itself relevant to quantum mechanics), which leads to rings and fields (widely applicable in linear algebra, analysis), which leads to other advanced topics.
    • I'm somewhat uncertain how to interpret your "If you think primes are boring..." remark.

      I think I know what you meant, but I think I like the literal "If you think primes are boring... take a class in abstract algebra" better. ;)
  • by Snoe ( 114590 ) on Wednesday November 10, 2004 @12:30AM (#10773767)
    The Prime Number Shitting Bear [surfeu.fi]. Watching a console window spit out prime numbers might do it for the geeks, but everyone can loves the prime number shitting bear.
  • Is the IOCCC entry one of the methods mentioned? :-p
  • by Theovon ( 109752 ) on Wednesday November 10, 2004 @12:42AM (#10773851)
    For those who scoff at this kind of stuff, we have to keep in mind that it's this sort of tinkering that results in some of the most amazingly useful and interesting stuff later.

    I have one lament, which is that his code formatting (indenting) got munged, making it really hard to read the code. I'm really tired, so I just couldn't manage to read through all the C code. I hope he fixes the page so that I can read it more easily later.
  • by jkleint ( 70681 ) on Wednesday November 10, 2004 @12:46AM (#10773876)
    As mentioned, DJB's primegen [cr.yp.to] is much faster. Even his Sieve of Eratosthenes implementation will do the primes up to a billion in 1.38 seconds on a 2.4 GHz P4, which is roughly 100x faster than this guy's "all primes below 100 million in less than 13 seconds" (although he doesn't specify on what machine). There's no reason to be using huge memory "pages," you can sieve up to N with any size interval you want (like say, the size of your L1 d-cache) using only Sqrt(N) memory for the primes up to Sqrt(N).
  • I am really surprised the author never mentions wheel factorization [utm.edu]. It makes the task even easier.
    Here [rsok.com] is my favorite program. It includes a 64-bit version.
  • this is something I wrote a while back to optimize my friend's prime finder he wrote to learn perl (I ported it to C and sped it up a LOT, although mine still sucks).

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char **argv) {
    unsigned long long maxprimes = atoll(argv[1]);

    printf("calculating %ld primes...\n", maxprimes);

    unsigned long long value = 1; //the last prime
    unsigned long long count = 0; //the count of primes found

    unsigned long long i = 0;

    for(count = 0; count < maxp

  • I just RTFA... (Score:5, Interesting)

    by acidblood ( 247709 ) <decio@@@decpp...net> on Wednesday November 10, 2004 @01:04AM (#10773957) Homepage
    ...and I'm going to list a few improvements here that I think the author missed.

    In one of the early programs, the author had the idea of skipping all even numbers, which are of course divisible by 2. In the next program he found out how he could skip numbers divisible by 3. One can make a systematic method out of that -- in the literature it's known as adding a wheel to the sieve of Erathostenes. Thing is, he implemented the sieve of Erathostenes foregoing this improvement he had implemented earlier. This leads to a big improvement: when using a wheel with the first four primes 2,3,5,7, there are only 48 residue classes out of 210 = 2*3*5*7 possible that are not divisible by any of these four primes. In practice this means that, for each 210 numbers you'd consider, the sieve would only need be applied in 48 of them. That's a gain of 4.375. One can make a gain of nearly 5 using a wheel of the first five primes, but it begins to get complicated.

    Another improvement would be to make the program cache-friendly. He sort of did this, down one level of the memory hierarchy, by paging the data to disk -- now he only needed to realize that, just as memory is much faster than disk, cache memory is faster than main memory. I've developed a sieve employing this optimization and it pays off indeed. This is considered a basic technique in the realm of high-performance computing. (The NFSNET, see my sig, uses a sieve including this and other optimizations, for instance).

    I might get flamed for this, but he should consider assembly programming. There aren't many applications where assembly will pay off so handsomely as this one, and the `core' of the sieve is very small, so only a few lines of assembly are needed. Vector integer instructions, such as MMX and the integer instructions of SSE2, can be employed to very good advantage here. My sieve program also included this, and it gives a real nice boost -- and only about 25 lines of assembly were used, the rest was C.

    Lastly there's the issue of representing the output. He stored the primes on disk by writing their values. A little compression can be realized in this representation: for instance he's printing out the primes in decimal, while hexadecimal would be more space-efficient. And instead of printing out the ASCII characters from 0 to 9, A to F, he could use a binary representation and read them through an hex dump -- that saves half the space, as a byte is used to store two hexadecimal digits instead of one.

    A perfectly good representation that could save a lot of space (8 times, to be precise) would be a bitmap, which he used on some of his programs. That's where you represent primality or lack of it by setting and clearing bits of an integer. It's pretty easy to determine a prime from a bitmap value, so this representation is just as good as the previous one. One could also use the wheel idea I explained before to save even more space: a concrete example would be that for each block of 210 numbers, one needs only bitmaps for 48 of them, as the rest are divisible by the first four primes. In this example a savings of 4.375 would be realized. Of course, all these ideas would require special readers programs, instead of just opening up the files in a text editor -- a small price to pay for such a large space savings.

    But in case only sequential reading of the primes is desired, there is an even more efficient representation: just write out the prime gaps, i.e. the difference between consecutive primes. One bit can be saved by realizing that, other than 3 - 2, all prime gaps are even, so one can just store the prime gap divided by two. One could really nitpick and point out that 0 is an impossible prime gap, so one could subtract two from all gaps, but this gain is too small to be worth the hassle. According to Thomas Nicely [trnicely.net] (incidentally the guy who discovered the bug on the Pentium FPU during his studies on computational number theory), one could store the prime gaps of all
    • Re:I just RTFA... (Score:4, Informative)

      by coyote-san ( 38515 ) on Wednesday November 10, 2004 @02:48AM (#10774416)
      You overlooked another key optimization - no number can have prime factors larger than sqrt(N). You don't need to bother computing any of the intermediate primes. With a 210-into-48 encoding you can quickly determine primality of any 32-bit number with a precomputed block of only 2k! This is such a small buffer that you could easily bootstrap it the first time the function is called - you can bootstrap the process by hardcoding nothing more than the first 6 bytes.

      This raises an interesting question - is it faster to load precomputed blocks from disk or to regenerate it in the L1 cache? One buffer would hold the first block, a second buffer would hold the 2nd-Nth block computed on demand, and a third buffer would hold the target block that's being updated by each successive block.

    • Re: I just RTFA... (Score:4, Informative)

      by Omniscient Ferret ( 4208 ) on Wednesday November 10, 2004 @05:33AM (#10774871)
      That's where you represent primality or lack of it by setting and clearing bits of an integer.
      Working out the mask for those bit operations can take enough time to cancel out the space benefits. I think you could optimize the different masks & their steppings.

      ... there is an even more efficient representation: just write out the prime gaps, i.e. the difference between consecutive primes.
      I tried this, but I don't know where that program is now. I used 0 as an escape code, allowing me to either note the next delta in hex, or else the current number, to detect errors. I only did this for output, though.

      I could see that being effective for the trial factor prime number table, too.

      Oh, and the nfsnet thing that's your homepage is cool.

      There's a primes program in (uh, on Debian) the bsdgames package; if memory serves, it does the wheel thing suggested.

      A suggestion for the article:
      If the trial factor prime number table gets big enough to swap (either out of cache, or out to disk), just segment the trial factors too.

      This is something I've given a lot of thought to; I've been interested in prime numbers since I was a kid. I've thought about making CDs or DVDs full of primes.
    • Re:I just RTFA... (Score:3, Informative)

      by johntromp ( 565732 )
      Covering 30 numbers per byte and precomputing all the bit-indices, one arrives at: http://www.cwi.nl/~tromp/pearls.html#sieve [www.cwi.nl]
  • "It was mentioned on CNN that the new prime number discovered recently is four times bigger than the previous record." --John Blasik

    "You know what seems odd to me? Numbers that aren't divisible by two." --Michael Wolf.

    "I don't get even, I get odder."

    How to prove that all odd numbers are prime? Well, this problem has different solutions whether you are a:

    • Mathematician: 1 is prime, 3 is prime, 5 is prime, 7 is prime, and by induction we have that all the odd integers are prime.
    • Physicist: 1 is prime, 3 is prime, 5 is prime, 7 is prime, 9 is an experimental error...
    • Engineer: 1 is prime, 3 is prime, 5 is prime, 7 is prime, 9 is prime...
    • Chemist: 1 prime, 3 prime, 5 prime... hey, let's publish!
    • Modern physicist using renormalization: 1 is prime, 3 is prime, 5 is prime, 7 is prime, 9 is ... 9/3 is prime, 11 is prime, 13 is prime, 15 is ... 15/3 is prime, 17 is prime, 19 is prime, 21 is ... 21/3 is prime...
    • Quantum Physicist: All numbers are equally prime and non-prime until observed.
    • Professor: 1 is prime, 3 is prime, 5 is prime, 7 is prime, and the rest are left as an exercise for the student.
    • Confused Undergraduate: Let p be any prime number larger than 2. Then p is not divisible by 2, so p is odd. QED
    • Measure nontheorist: There are exactly as many odd numbers as primes (Euclid, Cantor), and exactly one even prime (namely 2), so there must be exactly one odd nonprime (namely 1).
    • Cosmologist: 1 is prime, yes it is true....
    • Computer Scientist: 1 is prime, 10 is prime, 11 is prime, 101 is prime...
    • Programmer: 1 is prime, 3 is prime, 5 is prime, 7 is prime, 9 will be fixed in the next release, ...
    • C programmer: 01 is prime, 03 is prime, 05 is prime, 07 is prime, 09 is really 011 which everyone knows is prime, ...
    • BASIC programmer: What's a prime?
    • COBOL programmer: What's an odd number?
    • Windows programmer: 1 is prime. Wait...
    • Mac programmer: Now why would anyone want to know about that? That's not user friendly. You don't worry about it, we'll take care of it for you.
    • Bill Gates: 1. No one will ever need any more than 1.
    • ZX-81 Computer Programmer: 1 is prime, 3 is prime, Out of Memory.
    • Pentium owner: 1 is prime, 3 is prime, 5 is prime, 7 is prime, 8.9999978 is prime...
    • GNU programmer: % prime
      usage: prime [-nV] [--quiet] [--silent] [--version] [-e script] --catenate --concatenate | c --create | d --diff --compare | r --append | t --list | u --update | x -extract --get [ --atime-preserve ] [ -b, --block-size N ] [ -B, --read-full-blocks ] [ -C, --directory DIR ] [--checkpoint ] [ -f, --file [HOSTNAME:]F ] [ --force-local ] [ -F, --info-script F --new-volume-script F ] [-G, --incremental ] [ -g, --listed-incremental F ] [ -h, --dereference ] [ -i, --ignore-zeros ] [ --ignore-failed-read ] [ -k, --keep-old-files ] [ -K, --starting-file F ] [ -l, --one-file-system ] [ -L, --tape-length N ] [ -m, --modification-time ] [ -M, --multi-volume ] [ -N, --after-date DATE, --newer DATE ] [ -o, --old-archive, --portability ] [ -O, --to-stdout ] [ -p, --same-permissions, --preserve-permissions ] [ -P, --absolute-paths ] [ --preserve ] [ -R, --record-number ] [ [-f script-file] [--expression=script] [--file=script-file] [file...]
      prime: you must specify exactly one of the r, c, t, x, or d options
      For more information, type "prime --help''
    • Unix programmer: 1 is prime, 3 is prime, 5 is prime, 7 is prime, ...
      Segmentation fault, Core dumped.
    • Computer programmer: 1 is prime, 3 is prime, 5 is prime
    • You missed one:
      Slashdot:
      • New prime number 11 found posted by Hemos
      • Conservatives hide evidence of new prime number to confound encryption posted by Michael
      • 9's primeness stolen by Republicans posted by Timothy
      • Primeness in a post-9 world posted by Jon Katz
      • New prime number 2 higher than 9 found posted by CmdrTaco
  • by ajs318 ( 655362 ) <sd_resp2@earthsh ... .co.uk minus bsd> on Wednesday November 10, 2004 @10:05AM (#10775911)
    This was the method I used in my first attempt to write a prime-number generator. I figured that any positive integer can be written as 6n, 6n+1, 6n+2, 6n+3, 6n+4 or 6n+5 where n is an integer; and furthermore, 6n, 6n+2 and 6n+4 are definitely even, while 6n+3 is definitely a multiple of three. So we only need to try 6n+1 and 6n+5 to see if they are primes. Also, the smallest prime factor of a non-prime number must be smaller than or equal to its square root; so you don't need to try every known prime for divisibility. Rather than do a square root, though, I squared the testing_factor and compared it with the prime_candidate. This is quicker for small prime_candidates; but, as the list of known primes {and thus testing_factors} grows, eventually the many multiplications will start to take longer than one square root evaluation. The crossover point actually is a system-by-system variable, since it depends on FPU performance.

    I subsequently worked out that any list of primes stopping one shy of a product of primes-so-far {6, 30, 210, 2310 ..... } can be used, with very slight modification, as a sort of pre-sieve to eliminate things that are never going to be primes. For instance, looking at 30n+m, the "potential primes" are 30n+1, 30n+7, 30n+11, 30n+13, 30n+17, 30n+19, 30n+23 and 30n+29. {The primes smaller than 30 are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29; see how we simply have excluded everything which is a factor of 30, and included 1.} This list is good up to and including 209 {210 = 2 * 3 * 5 * 7} beyond which a new list will apply going something like 210n+1, 210n+11, 210n+13 ..... }

    Now this is beginning to look like a recursive process! Mind, we're getting longer and longer lists as the density of primes is getting smaller. Hmm ..... I think I might have to go and investigate .....
    • It appears you may be reinventing The Wheel [utm.edu]. (I always wanted to say that, sorry...) That article discusses using the wheel for factorization, but it can also be used for compact storage of primes in a bit array. For example, a bitmap corresponding to only odd numbers would be a "wheel size" of two. If you also drop every bit divisible by three, you have a "wheel size" of six.

      Surf around that site (http://primepages.org/ [primepages.org]), there's lots of good info there.

"Here's something to think about: How come you never see a headline like `Psychic Wins Lottery.'" -- Comedian Jay Leno

Working...