I wrote this simple code in python to calculate a given number of primes.
The question I want to ask is whether or not it’s possible for me to write a script that calculates how long it will take, in terms of processor cycles, to execute this? If yes then how?
primes = [2]
pstep = 3
count = 1
def ifprime (a):
""" Checking if the passed number is prime or not"""
global primes
for check in primes:
if (a%check) == 0:
return False
return True
while 1000000000>= count:
if ifprime(pstep):
primes.append (pstep)
print pstep
count += 1
pstep += 1
The interesting thing about this problem is that whether or not I find primes after x cycles of incrementation is something nearly impossible to predict. Moreover, there’s recursion happening in this scenario since the larger ‘prime’ list grow the longer it will take to execute this function.
Any tips?
I think you would have to use an approximation of the distribution of primes, a la PNT which (I think) states that between 1 and x you’ll have approximately
x/ln(x)primes (ln being natural log). So given rough estimates of the time taken for a single iteration, you should be able to create an estimate.You have approximately x/ln(x) primes in your list. Your main code block (inside the while loop) has constant time (effectively)…so:
t(x) ~ x/ln(x) * a + b + t(x-1)
where
t(x)is the time taken up to and including iteration x,ais the time taken to check each prime in the list (modulous operation), andbis the ‘constant’ time of the main loop. I faintly remember there is a way to convert such recursive functions to linear ones 😉