elz: (Default)
elz ([personal profile] elz) wrote in [community profile] intro_to_cs 2009-11-12 03:03 pm (UTC)

Okay, here's my slept-on-it version, with bonus wisdom gleaned from [personal profile] ungemmed. I succeeded in getting rid of the stored boolean and made the initial variable assignments a little less hackish. Hopefully. :)

def find_nth_prime(prime_to_find):
    n = 1
    primes = []
    if prime_to_find < 1:
        print "Please enter a number greater than zero."
        return None
    else:
        while len(primes) < prime_to_find:
            if len(primes) == 0:
                primes.append(2)
                print "%i is prime number #%i" % (primes[0], len(primes))
            else:
                root = math.sqrt(n)
                for prime in primes:
                    if n%prime == 0:
                        break                
                    elif prime > root:
                        primes.append(n)
                        print "%i is prime number #%i" % (n, len(primes))
                        break
            n = n + 2
        return primes[prime_to_find - 1]



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