The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catch the bug here :(
count=1 #to keep count of prime numbers
primes=() #tuple to hold primes
candidate=3 #variable to test for primes
while count<20:
for x in range(2,candidate):
if candidate%x==0:
candidate=candidate+2
else : pass
primes=primes+(candidate,)
candidate=candidate+2
count=count+1
print primes
print "20th prime is ", primes[-1]
In case you're wondering, count is initialised as 1 because I am not testing for 2 as a prime number(I'm starting from 3) and candidate
is being incremented by 2 because only odd numbers can be prime numbers. I know there are other ways of solving this problem, such as the prime number theorem but I wanna know what's wrong with this approach. Also if there are any optimisations you have in mind, please suggest.
Thank You
23 and 29 are the prime numbers between 20 and 30.
Check if a number is Prime or not using sqrt()from math import sqrt # Number to be checked for prime n = 9 flag = 0 if(n > 1): for k in range(2, int(sqrt(n)) + 1): if (n % k == 0): flag = 1 break if (flag == 0): print(n," is a Prime Number! ") else: print(n," is Not a Prime Number!
An easy way to determine if a number is prime is by trial division: divide the number n by all the integers less than n, and if no exact divisors–other than 1–are found, then n is prime. You can see how this becomes time-consuming as the value of n increases.
There is a nice Sieve of Eratosthenes generator implementation in test_generators.py:
def intsfrom(i):
while 1:
yield i
i += 1
def firstn(g, n):
return [g.next() for i in range(n)]
def exclude_multiples(n, ints):
for i in ints:
if i % n:
yield i
def sieve(ints):
prime = ints.next()
yield prime
not_divisible_by_prime = exclude_multiples(prime, ints)
for p in sieve(not_divisible_by_prime):
yield p
primes = sieve(intsfrom(2))
>>> print firstn(primes, 20)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With