| leonardo ( @ 2006-07-23 03:09:00 |
| Entry tags: | math, python |
Numeri primi - Prime numbers
Modulo Python per la gestione di numeri primi. Contiene funzioni per:
- trovare i numeri primi minori di un numero dato;
- trovare il numero primo successivo ad un numero dato;
- determinare se un numero è primo.
http://www.fantascienza.net/leonard
--------------------
Python module for prime numbers management. It contains functions to:
- find the prime numbers up to a given number;
- to find the prime number successive to a given number;
- to tell if a given number is prime.
http://www.fantascienza.net/leonard
Python code used to test primeQ function against gmpy (http://gmpy.sourceforge.net/):
import gmpy
from random import randint
for i in xrange(10000):
n = randint(2, 341550071728321)
if gmpy.is_prime(n) != int(primeQ(n)):
print n
Mathematica code used to test nextPrime function against Mathematica:succPrime[n_] := Block[{m = n + 1},
While[Not[PrimeQ[m]], m++ ];
m]
data = ReadList["c:\\datas\\data", Number];
succ = ReadList["c:\\datas\\succ", Number];
For[i = 1, i <= 45006, i++,
If[Mod[i, 500] == 0, Print["*"]];
If[
succPrime[ data[[i]] ] != succ[[i]],
Print[i]
]
]
Python code used to generate the data numbers loaded by the Mathematica code:from random import randint, seed
seed(1)
thresholds = (1373653, 25326001, 3215031751, 118670087467,
2152302898747, 3474749660383, 341550071728321)
testdata = list(thresholds[:-1])
last = thresholds[-1]
testdata.extend( randint(0, last) for x in xrange(10000) )
for n in thresholds[:-1]:
inf = int(n * 0.9)
sup = int(n * 1.1)
testdata.extend( randint(inf, sup) for x in xrange(5000) )
inf = int(thresholds[-1] * 0.9)
sup = thresholds[-1]
testdata.extend( randint(inf, sup) for x in xrange(5000) )
print "Numbers saved:", len(testdata)
file("data", "w").write( "\n".join(map(str, testdata)) )
Some similar code was used to test primeQ function against nextPrime.Python code used to write the "succ" file of prime numbers successive to the numbers contained in the "data" file:
numbers = map(int, file("data"))
print "Numbers:", len(numbers)
succ = []
for i, n in enumerate(numbers):
if i % 500 == 0: print i
succ.append( nextPrime(n))
file("succ", "w").write( "\n".join(map(str, succ)) )