Topic: MIT OCW PROBLEM SET SERIES 2/n
I have found really interesting the courses about Python at
I have decided to submit my solutions to the suggested problems. I do not think mine the best solutions possible, here i share them with you with the hope to have usefull feedback.
You can find the text of the problem in the site that I suggested, i will not repeat it here.
Here is the code for ps1b.
from math import *
def sumPrimesLogsTo(n):
"""Computes the sum of logs of primes < n"""
def divisible(curr,d):
"""Check if curr is divisible by an element of d"""
for i in d:
if (i > sqrt(curr)):
return False
elif (curr % i == 0):
return True
return False
def calculatePrimesLessThan(n):
"""Computes the primes less then"""
d = {1:2}
d1 = {}
idx = 2
cnt = 1
curr = 1+2*cnt
while (curr <= n):
if (not divisible(curr,d1.values())):
d1.update({idx:curr})
idx += 1
cnt += 1
curr = 1+2*cnt
d.update(d1)
return d
assert(n > 2)
assert(type(n)==type(1))
d = calculatePrimesLessThan(n)
res = 0.0
for v in d.values():
res += log(v)
return res
def problemSet1():
"""Verify for different values of n the sum of logs of primes < n"""
n = 3
res = sumPrimesLogsTo(n)
print 'Logs sum: ',res, 'n: ', n, 'ratio: ', res/n
n = 10
res = sumPrimesLogsTo(n)
print 'Logs sum: ',res, 'n: ', n, 'ratio: ', res/n
n = 100
res = sumPrimesLogsTo(n)
print 'Logs sum: ',res, 'n: ', n, 'ratio: ', res/n
n = 1000
res = sumPrimesLogsTo(n)
print 'Logs sum: ',res, 'n: ', n, 'ratio: ', res/n
n = 10000
res = sumPrimesLogsTo(n)
print 'Logs sum: ',res, 'n: ', n, 'ratio: ', res/n
n = 100000
res = sumPrimesLogsTo(n)
print 'Logs sum: ',res, 'n: ', n, 'ratio: ', res/nLast edited by 5tarson (February 5, 2012 15:07)