I came across the following solution for this problem: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset1a.pdf : def testPrime(x): factor = 2 while factor**2 <= x: if x % factor == 0: return False else: factor = factor + 1 return True candidate = 3 numPrime = 1 while numPrime < 1000: if testPrime(candidate): numPrime = numPrime + 1 candidate = candidate + 2 print "The 1000th prime number is", candidate - 2 I'm having a hard time understanding what's going on here, and was totally lost on the problem in the first place. How can I wrap my mind around this?
Without anything specific to address I will offer this, hopefully it helps. The first section of this code is defining a function, this is the meat of the program as it will be the part that does all of the work: def testPrime(x): // Define the name and input var of our function factor = 2 // Assign the variable an initial value while factor**2 <= x: // As long as our factor *2 is less than or equal to x, keep going if x % factor == 0: // If x divided by our factor has a remainder of 0, do this return False else: // Otherwise do this factor = factor + 1 return True /* Define two variables and give values */ candidate = 3 numPrime = 1 while numPrime < 1000: // While variable numPrime is less than 1000, keep going if testPrime(candidate): // If the function testPrime returns a true, do this numPrime = numPrime + 1 candidate = candidate + 2 /* Print the results */ print "The 1000th prime number is", candidate - 2
Awesome documentation eSpeX. This shows how important it is to learn to read code as well as to write it. You've done this before.
Join our real-time social learning platform and learn together with your friends!