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?
After fixing one little problem (and removing the output to make things cleaner) it works for me:
The problem being that your first
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..