I wrote this python code to find any prime number, the 1st, 2nd, 1000th, etc. I ran the code and it returned this, no matter what integer I entered:
2 is the 1 prime
3 is the 2 prime
5 is the 3 prime
7 is the 4 prime
Here is the code (written in python 2.7.8):
#code to find the nth prime
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n:
return False
# range starts with 3 and only needs to go up the squareroot of n for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
num_ofprimes = 0
candidate_prime = 2
final_primes = raw_input("What prime would you like to find?")
while num_ofprimes <= final_primes:
if isprime(candidate_prime) == True:
if candidate_prime == 2:
num_ofprimes = num_ofprimes + 1
print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
candidate_prime = candidate_prime + 1
#2 is prime
elif candidate_prime % 2 == 0:
candidate_prime = candidate_prime + 1
#if a number is even it is not prime
else:
num_ofprimes = num_ofprimes + 1
print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
candidate_prime = candidate_prime + 1
# checks all odd numbers to see if prime then prints out if true
print ("All done!")