exor674: Computer Science is my girlfriend (Default)
Dre ([personal profile] exor674) wrote in [community profile] intro_to_cs 2009-11-12 06:47 am (UTC)

from math import *

def primes_upto_n(n):
    primes = [2]
    choice = 1
    while len(primes) < n:
        choice += 2
        rt = sqrt(choice)
        isPrime = True
        # since we need all primes from 2 to n, this optimization works
        # we can prime-factor all non-prime numbers.
        for i in range(0, len(primes)):
            poss = primes[i]
            if (choice % poss) == 0:
                isPrime = False
                break
            if (poss >= rt):
                break
        if isPrime:
            primes.append(choice)
    return primes

primes = primes_upto_n(1000)
nthPrime = primes[-1]
sums = reduce(lambda sum,prime: sum+log(prime),primes)
print "Sum: ", sums
print "Nth Prime: ", nthPrime
print "sums / Nth Prime: ", sums/nthPrime


Yeah, this includes some weird-crazy optimizations >_<

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