Tuesday, September 14, 2010

Finding the 1000th Prime

I mentioned the other day the homework assignment for MIT OCW Intro to CS course was to find the 1000th square root. Here is a possible solution to the problem:

primeCheck = 5
primeCount = 3
while primeCount <= 1000:
    for divisor in range(2, primeCheck//2+1):
        remainder = primeCheck % divisor
        if remainder == 0:
            break
    else:
        primeCount += 1
    primeCheck += 1
print(primeCheck - 1)

*Note - Thanks go out to Nallo who helped make my original code with clarity.

You can see we've got a few new things here. The while loop on line 3, the for loop in line 4, and a few new uses for our operators. I started explaining everything new here and it became a fairly long explanation I split into two other posts so if you want the explanation you can go there and if you just wanted to see the code you can stop here. We could also have changed 1000 to variable and inserted >>>variable = input("What prime number do you want") in the front to make this code find just about any prime.
The result is 7919 which you can also see here: List of 1000 Primes

Related posts:
Finding the 1000th Prime: Explanation
While Loops
Declaring Variables with Python
Order of Operations

3 comments:

  1. Try using a sieve of eratosthenes and see how much faster it is.

    ReplyDelete
  2. i think that code is horrible. see this:

    http://pastebin.com/cAcdjJ4E

    it's more SICP-like. first i generate a stream of primes, THEN i pick the 1000th prime from that stream.

    i could have gone further and just had a primality test function, used it to filter (itertools.ifilter) an increasing sequence (itertools.count), then pick the 1000th element.

    ReplyDelete
  3. I'm just happy I made code that worked at all with the problem given to me since I'm still new but I will look into what both of you said. Thanks for the advice!

    @Cracki- How many primes would you go out to for the stream of primes. If you left it open it seems like it could go on forever collecting primes and never let you get to the step of picking one from that stream. I may just not understand fully what you are saying. Thanks again for the help.

    ReplyDelete