in reply to Math help: Finding Prime Numbers

Math::Pari is the gold standard for number-theoretic things in perl. It isn't trivial to install, but it can do anything that is practical with prime numbers. Nothing matches it for speed and range.

It has functions for primality testing, n-th prime, next higher prime from a number, and lists of primes. It can factor up to 60 digits or so very quickly. All the numbers are promoted to multiple precision at need. The libPARI library is used.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Math help: Finding Prime Numbers
by BrowserUk (Patriarch) on Nov 14, 2006 at 04:49 UTC

    Math::Pari is great--I wish I understood more of it than the ~1% that currently I do :)--but it's not so good for primes. By default (AS PPM version), primes() only knows the first 41561 primes:

    C:\test>p1 Perl> use Math::Pari qw[ prime primes nextprime precprime ];; Perl> print prime 41561;; 500257 Perl> print prime 41562;; PARI: *** not enough precalculated primes at (eval 7) line 1, <STDIN +> line 4.

    It will generate larger primes using nextprime(), but it pretty slow, taking around 64 seconds to get to the 1 millionth:

    Perl> print scalar localtime; $p = 500257; $p = nextprime ++$p for 41562 .. 1000000; print scalar localtime; print $p;; Tue Nov 14 04:36:02 2006 Tue Nov 14 04:37:07 2006 15485863

    But the biggest problem is that it forgets all the bigger primes as soon as it has returned them (below is a continuation of the previous session):

    Perl> print prime 41562;; PARI: *** not enough precalculated primes at (eval 9) line 1, <STDIN +> line 6.

    From the error message I guess it might be possible to increase the number of precalculated primes if you manage to build it yourself? But if you Linux guys have trouble with it, you can guess my chances :)


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      The $Math::Pari::initprimes variable controls initialization of precalculated primes. Since that doesn't go through the perl iface, but is a canned C routine, initialization is fast. To avoid setting that in a BEGIN block, you can say:

      use Math::PariInit qw( primes=12000000 );
      See the Initialization section of the Math::Pari docs.

      After Compline,
      Zaxo