Friday, July 8, 2011

MIT 6.00 Problem Set 1 - Problem 2 Answer

Iguana, Florida Everglades.

Python Code Answer:

#Problem Set 1 - Problem 2

#(sum of logs of all primes < nth prime) < nth prime
#(sum of logs of all primes < nth prime) / nth prime lim 1 as n --> inf

from math import log

candidate = 1
prime_count = 1
sum_log_prime = 2 

nth_prime = raw_input('find result for nth prime: ')
nth_prime = int(nth_prime)

while prime_count < nth_prime:
    divisor = 2
    prime = 1
    candidate += 2

    while divisor <= candidate**0.5:
        if candidate % divisor == 0:
            prime = 0
            break

        divisor += 1
                
    if prime:
        prime_count += 1

        sum_log_prime += log(candidate)

        if prime_count == nth_prime:
            print "results"
            print "nth prime: %i" % (candidate)
            print "sum of logs: %f" % (sum_log_prime)
            print "ratio: %f" % (sum_log_prime / candidate)

Results:

find result for nth prime: 1000
results
nth prime: 7919
sum of logs: 7813.590394
ratio: 0.986689


n where n is the nth prime: 25000
results
nth prime: 287117
sum of logs: 286496.402933
ratio: 0.997839


n where n is the nth prime: 100000
results
nth prime: 1299709
sum of logs: 1298475.739390
ratio: 0.999051


find result for nth prime: 200000
results
nth prime: 2750159
sum of logs: 2748035.363784
ratio: 0.999228



find result for nth prime: 500000
results
nth prime: 7368787
sum of logs: 7366417.756310
ratio: 0.999678


Had to go walk the dog for that one.
It takes a while to converge.



No comments:

Post a Comment