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 ' '

Post a comment in response:

This community only allows commenting by members. You may comment here if you're a member of intro_to_cs.
(will be screened if not on Access List)
(will be screened if not on Access List)
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting