I am trying to calculate prime numbers on a single machine, around the size of 2^30-2^100.
My algorithm is included below for anyone interested.
I've optimized this Python code to be O(sqrt(n/2))
(I believe) for each number: it only accepts odd numbers, and I ensure the number passed to it is odd in another method.
I used the Fermat primality test to try and speed up the process. However, the numbers are too large for the built-in math.pow()
method so I used Exponentiation by Squaring.
However, this is taking a very long time for larger numbers - which would be faster using just brute force.
Is my implementation wrong?
The time comes from the squaring algorithm, its recurrence stack also eats up my memory, is there a faster algorithm for this that I should research?
To calculate if the number 35184372088967 is prime, it took .00100111 seconds using my brute force algorithm, but took .40608 seconds to run the prime test.
Brute force prime number check:
def isPrime(n):
for i in range(3,int(math.sqrt(n)),2):
if(n%i==0):
return False
return True
Implementation of Fermat's algorithm:
def couldBePrime(n):
if(n>308):
return power(2,n-1)%n==1
else:
return math.pow(2,n-1)%n==1
Exponentiation by squaring algorithm (The time consuming part):
def power(base,exp):
if exp == 0:
return 1
elif exp == 1:
return base
elif (exp & 1) != 0:
return base * power(base * base, exp // 2)
else:
return power(base * base, exp // 2)