aranthe ([personal profile] aranthe) wrote in [community profile] intro_to_cs2010-03-24 06:42 pm
Entry tags:

PS1: Problem 1 » Solution

I haven't had time to edit Problem 2 yet, but will post it as soon as I do.

PS 1: Problem 1

# Initialize state variables.
primes = [2]
count = 1
sum_candidates = 0
sum_tests = 0

# Do this until we have 1000 primes
while len(primes) < 1000:

    # Increment counter by 2. (Eliminates all divisible by 2.)
    count += 2

    # Set prime switch true.
    is_prime = True

    # Loop through the testing slice.
    for prime in primes:

        # Check to see if count is prime.
        if count % prime == 0:

            # Not a prime, set switch to false.
            is_prime = False

            # Don't waste any more time on this number.
            break

        # Check for prime limit.
        if prime**2 > count:
            break

    # Check the switch; if it's still true...
    if is_prime:
        #...count is prime. Add it to the primes array.
        primes.append(count)

# print
ordinal = str(len(primes)) + 'th'
print 'The', ordinal, 'prime is', count
print ' '

npRfqttAoxHUGf

(Anonymous) 2012-01-07 08:33 am (UTC)(link)
Superb information here, ol'e chap; keep burning the mniidhgt oil.