I'm new to computer science and programming. I'm taking a free online class in coding, and one of the assignments was to write a program that will generate the 1000th prime number.
FYI, this is in Python 2.5.4
Here is the original code I copied (and edited a little bit) from another thread on this forum:
def isprime(n):
if n<2:
return False
else:
for i in range(2,(n/2+1)):
if n%i==0:
return False
else:
return True
def nthprime(n):
x=[]
j=2
while len(x)<n:
if (isprime(j)) == True:
x.append(j)
j =j+1
return(x[n-1])
print nthprime(1000)
However, I thought I could make the program faster by rewriting the isprime(n) function as follows:
def isprime(n):# First the primality test
i=1
if n<2:
return False
if (n!=2 and (n/2*2==n)):
return False
if n==3:
return True
if n==5:
return True
else:
while i <= (n/2+1):
i+=2
if n%i==0:
return False
else:
return True
That way, when it is only checking if n is divisible by odd integers (by this point in the code, we already know n is odd, and therefore not divisible by any even integers).
I thought that rewriting it this way would make the program work twice as fast (since it's only checking half as many numbers), but it seems to be taking the same amount of time, or even slightly longer, than what it was taking before.
Also, is there any way to rewrite the second block of code to get rid of the:
if n==3:
return True
if n==5:
return True
The only reason I included that is because I realized my algorithm was generating "false" for 3 and 5, even though they are prime.
Any help would be appreciated. Thank you.