Solutions for finding the 1000th prime

Neal rnlatimer at gmail.com
Fri May 21 03:19:56 EDT 2010


I'm doing the MIT OpenCourseWare class that this assignment hails from
and I don't doubt that its a relatively common assignment. Upon
searching for it for some ideas of why my program wouldn't work one of
the top results is this a thread from this group full of derision and
sarcasm. Believe me I understand that the people here don't want to do
another person's homework but for someone who isn't going to be coding
for a living or is a hobbyist like I am, there could be some useful
information. Eventually I figured out what I was doing wrong, and I
was hoping to add some insight. At this point in the lectures about
all we've learned to deal with as far as commands are: while, if,
else, elif and some boolean operators.

I started defining three variables I would need:
 One to count how many primes I have
 Which number I'm currently checking to be a prime
 Current number I'm dividing by as my checker

The assignment states that its easiest to check all odd integers > 1
but not to forget that 2 is a prime, easiest probably just to start
your counter at 1, I didn't but it took an extra 3 lines just to get
my counter to 1, and then get to the next number I'm checking all
without being in a usable loop.

You start your loop with the stated condition, no need for it to run
any more past counting the 1000th prime.

You could have your program check to see if a number is divisible by
every number less than itself and if so moving on to your next number.
However you do know that any number isn't going to be divisible by
another number in that sequence until it reaches itself divided by 2.
If you keep in mind though that we are only dealing with odd numbers,
you know that they will not be divisible by two, so instead we can
move on to itself divided by 3.

Every iteration of the loop when it finds a prime, needs to increase
the count, move onto the next candidate you're checking, and redefine
the divisor you're starting to check next time around. If a number is
determined not to be a prime you need to move onto the next candidate
and redefine your divisor (which is where I was stuck for a long time
writing this program). If your not sure that the number is a prime or
not a prime you simply need to redefine the divisor and continue the
loop.



More information about the Python-list mailing list