I've written some code to calculate the 'n'th prime number. There are issues when calculating the 25th prime and above (n=25 gets 95). Here's my code, please help me out if you can see my problem!
n=int(raw_input("This program will give you the nth prime number. Please enter n:")) if n == 1: print "the 1st prime is: 2" #the first prime is 2! else: if n<= 0: #if user inputs a negative n print "n must be >= 1" # can't calculate a -nth prime! else: counter = 1 prime = 1 # 2 is the first prime number while counter<n: #to stop at the desired nth prime number prime += 2 for divisor in range(2,prime/2): #too check for divisors up to 1/2 number if prime%divisor == 0: #a remainder means devisor means not a prime prime += 2 #check next prime print prime counter += 1 #next counter to continue the loop print"The ",n,"th prime is: ", prime
In python btw. Thanks!
95 is correct. next is 101. problem is?
95 isn't a prime number!
I recomend you to use the Sieve of Eratosthenes: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
ah yes sorry, i missread 95 and 97, sleepyness ;)
I really don't know Python, but I think the error may be in this part: for divisor in range(2,prime/2): if prime%divisor == 0: prime += 2 #when you do that you MUST reset divisor variable print prime You can put some like that: for divisor in range(2,prime/2): if prime%divisor == 0: prime += 2 divisor = 2 print prime
A modulus of zero means that the divisor divided into prime evenly, so whatever the variable prime contains isn't a prime number. And if one number doesn't divide with modulus of zero, they all have to. I took a much different approach: primes = [ 2, 3 ] testNum = 5 numberOfPrimes = 10000 while( len( primes ) < numberOfPrimes ): for i in xrange( 0, len( primes ) ): if( testNum % primes[i] ): if( i == ( len( primes ) - 1 )): primes.append( testNum ) else: break testNum += 2 lastPrime = primes[len( primes ) - 1] print "The", str( numberOfPrimes ) + "th prime is:", lastPrime
I don't know Python, but here is an algorithm in pseudo code that will work if you appy it no matter what language you are programming in. maxValue = 50 //The maximum value to be checked isPrime = true //Is true if we find a prime //Check all values from 2 to maxValue OuterLoop for i = 2 to maxValue isPrime=true //Assume the current i is prime //Try dividing by all integers from 2 to i-1 for j = 2 to i - 1 if i modulus j == 0 //This is true if j divides exactly continue with OuterLoop //so exit loop //We can only get here if wwe have a prime, so . . . print i This is pretty much what rsmith6559 said, just using pseudo code instead.
Join our real-time social learning platform and learn together with your friends!