Slashdot Mirror


Fun with Prime Numbers

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."

90 of 472 comments (clear)

  1. Obligatory by zedmelon · · Score: 5, Funny

    This article will be a prime target for bad jokes.

    --
    Mom says my .sig can beat up your .sig.
    1. Re:Obligatory by spellraiser · · Score: 2, Funny

      Don't worry ... I've got a grenade primed, ready to blow all the bad jokes to smithereens.

      --
      I hear there's rumors on the Slashdots
    2. Re:Obligatory by Anonymous Coward · · Score: 5, Funny

      We must not be divided on this issue.

    3. Re:Obligatory by dtfinch · · Score: 2, Funny

      7*191=1337

    4. Re:Obligatory by dtfinch · · Score: 3, Interesting

      0x1337 is prime

    5. Re:Obligatory by Trejkaz · · Score: 3, Funny

      Luckily when it comes to the quality of a Slashdot comment, bad jokes don't factor into it.

      --
      Karma: It's all a bunch of tree-huggin' hippy crap!
    6. Re:Obligatory by eclectro · · Score: 3, Funny

      This article will be a prime target for bad jokes

      It's true. Good jokes come alomg only so often, and we don't know when.

      --
      Take the cheese to sickbay, the doctor should see it as soon as possible - B'Elanna Torres, "Learning Curve"
    7. Re:Obligatory by conan776 · · Score: 3, Funny

      God sieve us from these bad puns....

      --
      "Reality is that which, when you stop believing in it, doesn't go away." -- Philip K. Dick
    8. Re:Obligatory by Surazal · · Score: 3, Funny

      Not only don't we know when, we don't remember the last time, either.

      --
      --- Journals are boring; Go to my web page instead
    9. Re:Obligatory by Hognoxious · · Score: 2, Funny

      Yes, they'll certainly be abundant, especially from the people who are deficient. Still, I shouldn't complain - nobody's perfect.

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
  2. Where is it? by TamMan2000 · · Score: 3, Funny

    I got a 404...

    --
    "I'll have a Guinness, no wait, make that a Coors Light" -Grad student I work with, who shall remain anonymous...
    1. Re:Where is it? by zedmelon · · Score: 3, Informative
      --
      Mom says my .sig can beat up your .sig.
    2. Re:Where is it? by canwaf · · Score: 5, Funny

      Sorry, 404 isn't a prime number. Try again.

    3. Re:Where is it? by Baelrun · · Score: 3, Funny

      I got a 404.. That's not a prime number. No wonder the algorithm is so fast.

  3. This begs the question: by Anonymous Coward · · Score: 4, Insightful

    Why not just save primes on a disk instead of recalculating them all the time?

    1. Re:This begs the question: by Anonymous Coward · · Score: 5, Funny

      Why waste disk space with primes instead of just recalculating them?

    2. Re:This begs the question: by psetzer · · Score: 3, Insightful

      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.

      --
      "Anyone who attempts to generate random numbers by deterministic means is living in a state of sin." -- John von Neumann
    3. Re:This begs the question: by Dasein · · Score: 4, Informative

      There are a lot of them.

      As a matter of fact 2048 bits can represent numbers up to 2^2048 ~= 3.23x10^616. By the Prime Number Theorem 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)

      --
      You are not a beautiful or unique snowflake -- but you could be if you got off your ass.
    4. Re:This begs the question: by Goalie_Ca · · Score: 2, Funny

      Why waste time or space?

      --

      ----
      Go canucks, habs, and sens!
    5. Re:This begs the question: by Omniscient+Ferret · · Score: 4, Informative

      On my computer, generating primes from 2 to 2^32 takes a third of the time to unbzip2 the same list.

    6. Re:This begs the question: by maxwell+demon · · Score: 4, Interesting

      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).

      --
      The Tao of math: The numbers you can count are not the real numbers.
    7. Re:This begs the question: by StyroCupMan · · Score: 5, Funny
      If each number only has a 0.000703 chance of being prime, we can simplify this whole calculation with this function (pseudo-coded):

      boolean isPrime(int Number) {
      return false;
      }
      That function is 92.97% accurate. That's an A-. Good enough for me. :)
      --
      If I may say so, life is a game, and there's so much to do and so few turns.
      -Reiner Knizia
  4. Ugliest. Brace. Style. by onallama · · Score: 2, Informative

    EVER!!!

  5. What is special about prime numbers? by Dancin_Santa · · Score: 3, Insightful

    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?

    1. Re:What is special about prime numbers? by onallama · · Score: 2, Informative

      Well, considering that all positive integers > 1 are either prime themselves (e.g., 2, 3, 5, 7, 11...), or if not, can be expressed as the product of various primes (e.g., 4 = 2 * 2, 6 = 2 * 3, 8 = 2 * 2 * 2, 9 = 3 * 3, 10 = 2 * 5...), you could say that prime numbers are the building blocks of all integers, which is kind of cool...

    2. Re:What is special about prime numbers? by MillionthMonkey · · Score: 3, Interesting

      Brief overview. There is also the Prime Spiral.

    3. Re:What is special about prime numbers? by Jazzer_Techie · · Score: 5, Interesting

      I do not 'get' what is interesting or useful about prime numbers.

      Prime numbers are useful in encyption, but those are very large primes that are difficult to factor. To a mathematician, prime numbers are fascinating. The distribution of primes, which is specifially random but generally predictable (check out the MathWorld article for more details) is of particular interest.

      For example, the Riemann Zeta Function of n, which is the infinite sum of all terms k^(-n)[k varies from one to infinity], is expressable as the infinite product (1-p1^(-n))*(1-p2^(-n))*(1-p3^(-n))... [where pn is the nth prime number]. This is a mind-boggling connection. For example Zeta(2)= (pi^2)/6 = (1 + 1/2 + 1/4 +1/8 ...)= ((1-2^(-2))*(1-3^(-2))*(1-5^(-2))...) There is therefore a connection between pi and the distribution of the primes. Math is crazy stuff.

    4. Re:What is special about prime numbers? by rubee · · Score: 2, Informative

      It has applications in abstract algebra (like group theory) and number theory. Besides cryptography, they are often used in pseudo-random number generators and hash tables. check out: http://en.wikipedia.org/wiki/Prime_numbers

    5. Re:What is special about prime numbers? by notthe9 · · Score: 2, Informative

      Worth knowing, yes. It does, however, stem directly from what primacy means.

      Basic logic:

      for some number, it is either prime or a product of two numbers

      those numbers are either prime or a product of numbers

      those numbers are either prime or a product of numbers...

      and so on. Until all the numbers being multiplied are prime, they can always be factored into numbers that can be factored further (which meet the same criteria) or are prime.

      Since primes are integers that cannot be factored, they are clearly going to be the ones left.

    6. Re:What is special about prime numbers? by Anonymous Coward · · Score: 2, Funny

      Hand in your geek membership card. now.

    7. Re:What is special about prime numbers? by Anonymous Coward · · Score: 2, Funny

      "very large primes that are difficult to factor."

      I can go even further and say that those large primes are IMPOSSIBLE to factor!

    8. Re:What is special about prime numbers? by Smokybfgs · · Score: 2, Informative

      Throughout history, mathematicians have been fascinated with prime numbers - the sheer concept of indivisibility is one aspect (I mean, here they have numbers of infinite possible size that cannot ever be taken down into smaller whole units), and at the same time, these primes are the building blocks of all other numbers. Many great mathematicians have talked of prime numbers and developed more theories on them. Euclid proved there was an infinite number of prime numbers (basically showing that given any number of prime numbers, he could create a bigger prime number, or a number who had as a factor a prime number not included in this n). Riemann had his famous zeta function about the distribution of primes. We've named a great piece of beef after them (ok, not really, but I couldn't help the corny joke). Long story short, prime numbers seem fascinating (at least to me) because they are the building blocks, they are indivisible, and they seem to appear at random (that is, unless we can prove the Riemann Hypothesis) :-) That said, I concede prime numbers hold very little interesting value to many of those who find math too blah (the distribution of prime numbers mystery is hardly the mystery of the fate of Atlantis!)

  6. "FUN with Prime Numbers" by noisymime · · Score: 2, Funny

    I find that title so hard to appreciate, maybe I'm just not as big a geek as i thought.

    1. Re:"FUN with Prime Numbers" by wwahammy · · Score: 2, Funny

      I've never found prime numbers to be fun at all. Derivatives on the other hand....

  7. This can't be good by Anonymous Coward · · Score: 2, Funny

    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.

  8. Interesting code by icekillis · · Score: 2, Interesting

    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

  9. chosing typesafety over speed? by Anonymous Coward · · Score: 3, Funny

    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.

  10. Re:Mersenne by back_pages · · Score: 2, Informative
    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.

  11. The author isn't a lightweight ... by xmas2003 · · Score: 4, Interesting
    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

    --
    Hulk SMASH Celiac Disease
  12. Encryption by sbszine · · Score: 4, Interesting
    --

    Vino, gyno, and techno -Bruce Sterling

    1. Re:Encryption by sbszine · · Score: 5, Interesting

      Yeah, but that's an example of them being useful. It doesn't really make them esthetically "interesting".

      In that case I refer you to the fundamental theorum of arithmetic, which I think is pretty interesting.

      --

      Vino, gyno, and techno -Bruce Sterling

  13. Prime Resource by d3m057h3n35 · · Score: 2, Interesting

    Here's a nice, fun little resource for those interested in prime numbers. Actually, it's pretty large and exhaustive: The Prime Pages. Make sure to check out Prime Curios!; fascinating stuff.

  14. Have some more fun with primes by pestilence4hr · · Score: 4, Informative

    A very fast segmented sieve (to find primes in an arbitrary range) can be found here, by Tomás Oliveira e Silva.

    Of tangential interest is his Goldbach conjecture verification project. You can download his client and contribute to the project. He's shooting for 10^18...

  15. superior algorithm by Anonymous Coward · · Score: 2, Interesting

    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.

  16. the factor command in Unix/Linux by 3770 · · Score: 4, Interesting

    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.

    --
    The Internet is full. Go Away!!!
    1. Re:the factor command in Unix/Linux by 0racle · · Score: 5, Funny

      You don't really have friends do you.

      --
      "I use a Mac because I'm just better than you are."
    2. Re:the factor command in Unix/Linux by 3770 · · Score: 2, Funny


      Not among humans. And they are the only ones with phones.

      This is why I'm sharing this with the rest of you so that someone can use it.

      --
      The Internet is full. Go Away!!!
    3. Re:the factor command in Unix/Linux by bob+beta · · Score: 3, Funny

      If you want to be a true geek, you run factor against all the spare quartz crystals and oscillator blocks in your junkbox, to see which ones factor down to useful frequencies. 'A multiple of 9600 baud, hmmm....'

    4. Re:the factor command in Unix/Linux by AxelBoldt · · Score: 2, Informative

      By the prime number theorem, the probability that a given 7-digit number is prime is about 1/ln(10^8), which is roughly 5%. So the probability that two randomly picked numbers is prime is about 0.25%.

  17. Re:This begs the question by YGingras · · Score: 5, Informative
    What's the 1,716,050,470th prime?
    The 1,716,050,470th prime is 40,100,000,093.

    Find out more on the Nth Prime Page.
  18. Oh, that works on your friends, on /. on the... by 3770 · · Score: 2


    Oh, that works to make your friends think you are a geek.

    On /. on the other hand I suggest that you reply to my parent post, informing the world that you already knew of this puny little command and then proceed to talk about some _really_ obscure Linux command that only works on Slackware for the s/390 distro.

    --
    The Internet is full. Go Away!!!
  19. Gaps between primes by tbjw · · Score: 5, Interesting

    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.

  20. That's nice, but... by gibs · · Score: 2, Insightful

    Can someone tell me again what the point of this is?

  21. The largest known prime is... by stevok · · Score: 2, Informative
    2^24036583-1, 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 doesn't do the number justice. In fact, the cached number is divisible by 2...

  22. Prime Numbers for cash! by kuzb · · Score: 3, Interesting

    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. They give some good information about what prime numbers are, and what they're good for.

    --
    BeauHD. Worst editor since kdawson.
  23. Re:Complaint about article by shamilton · · Score: 2, Insightful

    The article feels like it was written for the sole purpose of showing off the author's knowledge. Perhaps I'm just hyper-sensitive to that...

    --
    "[A] high IQ is like a Jeep; you will still get stuck, just farther from help!" --Just d' FAQs, c.g.a
  24. Fun with primes? by The+Master+Control+P · · Score: 3, Funny

    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...

  25. Re:Mersenne by acidblood · · Score: 2, Informative
    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.
    --

    Join the NFSNET. Our prime goal is making little numbers out of big ones. http://www.nfsnet.org/

  26. First shitting bear post! by imag0 · · Score: 2, Interesting

    Now, who can forget the Prime Number Shitting Bear?

  27. Improvement by acidblood · · Score: 3, Insightful
    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 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.
    --

    Join the NFSNET. Our prime goal is making little numbers out of big ones. http://www.nfsnet.org/

  28. Re:A better use? by benna · · Score: 4, Informative

    encryption.

    --
    "It is not how things are in the world that is mystical, but that it exists." -Ludwig Wittgenstein
  29. Prime numbers in bad music... by Kenja · · Score: 2, Funny

    "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"

    --

    "Have you ever thought about just turning off the TV, sitting down with your kids, and hitting them?"
  30. Reminds me of... by constandinos · · Score: 2, Funny

    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

  31. If you think primes are boring... by rubee · · Score: 2, Informative

    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.

  32. Not as much fun as by Snoe · · Score: 5, Funny

    The Prime Number Shitting Bear. Watching a console window spit out prime numbers might do it for the geeks, but everyone can loves the prime number shitting bear.

  33. This is actually the MOST important thing to do! by Theovon · · Score: 3, Interesting

    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.

  34. Re:Mersenne by back_pages · · Score: 2, Informative
    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.

  35. Better Implementation by jkleint · · Score: 3, Interesting

    As mentioned, DJB's primegen 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).

  36. I just RTFA... by acidblood · · Score: 5, Interesting

    ...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 (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

    --

    Join the NFSNET. Our prime goal is making little numbers out of big ones. http://www.nfsnet.org/

    1. Re:I just RTFA... by coyote-san · · Score: 3, Informative

      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.

      --
      For every complex problem there is an answer that is clear, simple, and wrong. -- H L Mencken
    2. Re:I just RTFA... by BigBadDude · · Score: 2, Informative


      check this one out:

      http://cvs.sourceforge.net/viewcvs.py/buddy/budd y/ src/prime.c?view=markup

      (there are zillions more, but this page was the one that i had in memory)

    3. Re: I just RTFA... by Omniscient+Ferret · · Score: 3, Informative

      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.

    4. Re:I just RTFA... by acidblood · · Score: 3, Informative
      The GMP library uses a probabilistic algorithm as documented here. This is not as bad as it sounds. For instance, Dan Bernstein suggests in this paper a probabilistic procedure which consists of some trial factoring, a strong probable prime test and a Lucas test. Quoting him:

      There is no known example of a composite number p that slips past all of these tests; I'm confident that nobody will ever find one by accident.

      Of course, if you absolutely have to be sure that you're dealing with a prime, you could use a probabilistic algorithm to sieve for probable primes, then apply the n-1 test to obtain a primality certificate for your probable prime (which then becomes a certified prime with 0% probability of being composite). Of course this would be a bit costly, but for small integers the n-1 test is hard to beat -- ECPP and APR-CL have just too much overhead at this range. But I'm pretty sure your application, whatever it is, can live with the small probability that a PrP is composite.
      --

      Join the NFSNET. Our prime goal is making little numbers out of big ones. http://www.nfsnet.org/

    5. Re:I just RTFA... by johntromp · · Score: 3, Informative

      Covering 30 numbers per byte and precomputing all the bit-indices, one arrives at: http://www.cwi.nl/~tromp/pearls.html#sieve

  37. Fun with C by SirShadowlord · · Score: 2, Interesting
    Okay, could somebody explain to me (who hasn't touched C in about 10 years), a couple things about this code.

    First, what's with the %ull format specifier in sprintf - is that even a valid format specifier?

    Next, why subtract 2 from your buffer length when printing?

    Finally, why bother with the "printprime" and sprintf function altogether - is there anything wrong with:
    if (prime) printf("%llu\n",candidate);
    Okay, this is kind of nitpicking, but I'm clearly missing something obvious here...
    --
    - Any Day above Ground is a good Day (Michael Rich, 1997)
  38. Re:Mersenne by acidblood · · Score: 2, Informative
    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 prime numbers are not Mersenne numbers, which is an unrelated concept

    I can only suggest you to heed your own advice.
    --

    Join the NFSNET. Our prime goal is making little numbers out of big ones. http://www.nfsnet.org/

  39. Re:A better use? by eclectro · · Score: 2, Funny

    Excuse my ignorance, but what are extremely large primes used for?

    Obviously to get a date with a hot chic so you can impress her with the math you know.

    --
    Take the cheese to sickbay, the doctor should see it as soon as possible - B'Elanna Torres, "Learning Curve"
  40. Re:Variable structure for the lazy? by pkhuong · · Score: 2, Informative

    Well, depending on the architecture and the languages, linked lists can be easy :)

    http://en.wikipedia.org/wiki/VList

    "In computer science, the VList is a persistent data structure designed by Phil Bagwell in 2002 that combines the fast indexing of arrays with the easy extension of cons-based (or singly-linked) linked lists.

    Like arrays, VLists have constant-time lookup on average and are highly compact, requiring only O(log n) storage for pointers, allowing them to take advantage of locality of reference. Like singly-linked or cons-based lists, they are persistent, and elements can be added to or removed from the front in constant time. Length can also be found in O(log n) time."

    "The underlying structure of a VList can be seen as a singly-linked list of arrays whose sizes decrease geometrically; in its simplest form, the first contains the first half of the elements in the list, the next the first half of the remainder, and so on."

    For some reason, the article affirms that the VList is immutable.

    --
    Try Corewar @ www.koth.org - rec.games.corewar
  41. Re:Mersenne by acidblood · · Score: 4, Informative

    I'd venture to say I know what I'm talking about. One can't publish a paper about large-scale distributed primality proofs without knowing these basics. Here's a sample of my work. Now don't get me wrong, I'm not trying to sound like a smart-ass, but I'm not going to let someone question my knowledge in this field (which I have studied for years) and remain quiet.

    Now it seems people here are not familiar with the terminology associated with Mersennes, so I'll give a crash course.

    A Mersenne number M_n is of the form 2^n - 1. If 2^n - 1 is prime, then M_n is a Mersenne prime. If 2^n - 1 is composite, then M_n is a Mersenne composite. The integer n in this expression is called the exponent. When I talk about `exponents of Mersenne composites', I'm refering to some prime n for which M_n = 2^n - 1 is composite.

    Now if 2^n - 1 is prime, then n must be prime, but the converse is not always true, the smallest counterexample being 2^11 - 1 = 2047 = 23*89. Turns out that for prime exponents n = 24,036,583, only in 41 cases is 2^n - 1 actually prime. A list of these cases can be found here. For the other 1,509,222 prime values of n = 24,036,583, 2^n - 1 is composite. This translates to a compositeness ratio of 99.9973%.

    I hope everything is clearer now.

    --

    Join the NFSNET. Our prime goal is making little numbers out of big ones. http://www.nfsnet.org/

  42. also doesn't make sense by Trepidity · · Score: 2, Insightful

    Shouldn't any decent optimizing compiler (gcc?) inline those commonly-called functions anyway?

  43. Public Key Encryption by AT · · Score: 2, Informative

    Prime numbers are used in public key encryption. This type of encryption relies on having a function that is easy to generate, but very difficult to reverse. Factorization of large numbers is exactly the function that is used in practice: the prime factors of a large number can easily be multiplied together to get an even larger number, but getting those prime factors back from the giant number is hard. In fact, as the giant number size increases linearly, the time to calculate the factors increases exponentially (using the best known algorithms).

  44. How to prove that all odd numbers are prime by dargaud · · Score: 5, Funny

    "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
    --
    Non-Linux Penguins ?
    1. Re:How to prove that all odd numbers are prime by Kynde · · Score: 2, Informative

      Yeah, all those people seem to be under the delusion that one is prime... The number one is neither prime nor composite though (you'd think the mathematician in the joke would know that).

      Actually, 1 not being a prime is more of a consensus than a mathematical fact.

      Primes could be defined so that 1 is also a prime, it's just that way too many theorems we have these days would need to be refined to deal with 1 properly (starting with the fundamental theorem of arithmetics). Which is almost the same as to say, things are easier when 1 is not regarded a prime. But that doesn't imply that 1 is not a prime.

      One could argue that it would be more practical if a positive interger would either be a composite or a prime. Because positive integers now split into three classes: Primes, composites and 1. Meaning that negating prime theorems for composites require special handling with 1.

      Now, I wouldn't go telling anyone that 1 is a prime. But I'd be lieing if tried to claim that I remember to include it as an option when I'm assuming a number to be a prime when I've discovered that it's not a composite. Moreover, I must admit that, deep down, I do think of it as prime. It's just that the consensus is to leave it out of the equations, just like when we hop from N to Z+, to make things a little bit easier.

      --
      1 Earth is warming, 2 It's us, 3 it's royally bad, 4 we need to take action NOW
  45. Re:This begs the question by bertas28 · · Score: 3, Funny
    This somehow reminds me of a series of memorandum I came across in Paradox, a magazine published by the Melbourne Uni Math Society (MUMS).

    It consists of a bunch of proofs that there is no largest prime - the list of proofs is entitled "15 good reasons why Pure Mathematics is not taught to first year students." My favourites are:
    Proof by example:
    "Let x be the largest prime. Then x=91 but 91+6=97 which is prime. Therefore 91 cannot be the largest prime number. Therefore there is no largest prime."

    Proof by intuition:
    "Prime numbers are integers that can be divided by themselves only; prime numbers are odd with the exception of 2. By intuition as n->infinity, there will always be an odd number cannot be divided by another number besides itself."

    Proof by experimental data:
    "Suppose n is the highest prime. Then 2n-1 is also prime. But 2n-1>n so there is no highest prime. (Check: 2*2-1=3, 2*3-1=5, 2*5-1=11, 2*11-1=23, so true.)"

    But the greatest of them all:
    Proof by having no idea what a prime is:
    "Say the largest prime is x, then 2x is also a prime since the statement is true for all natural numbers."

    Go to http://www.ms.unimelb.edu.au/~paradox/archive/ for the magazine, these proofs appeared in issue 2 of 2002.

  46. Re:Give it up; this battle is a lost cause. by BJH · · Score: 2, Insightful

    If the primary existence of the Earth was as a collective consensus among humans, yes.

    You're comparing apples and oranges here. Language does not exist as an objective reality; it relies entirely upon the internal representation of that language shared between its speakers. If in the future nobody understood that language, it would no longer "exist" in any meaningful sense, whereas the Earth exists independently of the internal reality any human (or other being) holds to be true.

    In other words, the only way a language can be said to exist is as a "mainstream belief" of its speakers. So, you lose.

  47. You missed one by wowbagger · · Score: 2, Funny
    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
  48. Alternately adding 2 and 4 by ajs318 · · Score: 2, Interesting

    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 .....

    --
    Je fume. Tu fumes. Nous fûmes!
    1. Re:Alternately adding 2 and 4 by antispam_ben · · Score: 2, Informative

      It appears you may be reinventing The Wheel. (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/), there's lots of good info there.

      --
      Tag lost or not installed.
  49. Re:Mersenne by fatphil · · Score: 2, Interesting

    Yves Gallot's GFN (generalised Fermat Number) search, and my GEFN (generalised Eisenstein Fermat Number) search, are both as efficient when it comes to the primality tests. If anything, our tests might be more efficient, as our DWTs are simpler than Mersenne's IBDWT. Both of our forms are definitely more efficient than Mersennes, as we can _presieve_ ours to massively reduce the number of lengthy tests that we need to do.

    The only reason GIMPS (great internet mersenne prime search) has the top ?4 primes at the moment is because they have 1000x as much CPU power as Yves' GFN search, and 10000x as much CPU as my GEFN search.

    With Percival's generalised DWT algorithm, those searching for Proth/Riesel forms (k*2^n+/-1) with very small k also have a similarly efficient primality tests.

    The age of Mersennes is only not over yet because of the fact that they have such a head start. They will be caught up with over time when other projects get similar quantities of CPU power.

    FP.

    --
    Also FatPhil on SoylentNews, id 863
  50. Eliminate More Redundant Checks by CarbonRing · · Score: 2, Interesting

    There are a couple of easy improvements that can be made to Mr. Litt's program that I haven't seen mentioned.

    When removing multiples of a new prime p, you don't need to test the even multiples of p, 2 already did that for you. This cuts your work in half.

    Although less asymptotically beneficial, you can start with p^2 since the lower multiples of p have already been done in previous passes.