Reputation: 23
Here is a program that I wrote in Python:
import sys
from time import time
start = time()
x = input('How many primes? ')
if x < 1:
sys.exit("invalid input")
y = 3
primes = [2]
while len(primes) < x:
for i in primes:
if y % i == 0:
break
elif i > (y**(.5)):
primes.append(y)
break
y += 1
print primes
print time() - start
It works well, but I have noticed something strange. If I ask for 1000 primes, the program takes about 2.3 seconds to find an answer, but if I ask for 10000 primes, the program takes about 1.8 seconds to find an answer. This doesn't make much sense because the program has to do more calculations to find 10000 primes than 1000. Can anyone explain what is causing this?
Upvotes: 0
Views: 50
Reputation: 49187
you might want to sample your start time after the user input :)
after moving it, it ran in 0.012 seconds for 1000 and 0.365 seconds for 10000
Upvotes: 1
Reputation: 353059
After fixing one little problem (and removing the output to make things cleaner) it works for me:
~/coding$ python pcount.py
How many primes? 1000
0.0194370746613
~/coding$ python pcount.py
How many primes? 2000
0.0495121479034
~/coding$ python pcount.py
How many primes? 5000
0.172223091125
~/coding$ python pcount.py
How many primes? 10000
0.449481010437
The problem being that your first
start = time()
line comes before you ask for user input. You're not timing how long it takes to do the calculations, you're timing how long it takes you to enter numbers..
Upvotes: 1