MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 2, HW 1
#Problem 1
number_of_primes = 0
candidate = 0
test = 0
remainder = 0
while (1):
candidate = candidate + 1
#test primality
#1 if prime, 0 if not
for test in range(candidate):
remainder = (candidate)%(test + 1)
if remainder == 0 and (test + 1) <> 1 and (test + 1) <> candidate:
#not prime
break
if (test + 1) == candidate and candidate <> 1:
number_of_primes = number_of_primes + 1
if number_of_primes == 1000:
print 'The %dth prime is %d' % (number_of_primes, candidate)
break
#Problem 2
from math import *
number_of_primes = 0
candidate = 0
test = 0
remainder = 0
total = 0
ratio = 0
while (1):
candidate = candidate + 1
#test primality
#1 if prime, 0 if not
for test in range(candidate):
remainder = (candidate)%(test + 1)
if remainder == 0 and (test + 1) <> 1 and (test + 1) <> candidate:
#not prime
break
if (test + 1) == candidate and candidate <> 1:
#prime
total = total + log(candidate)
number_of_primes = number_of_primes + 1
if candidate == 1000:
ratio = total / candidate
print 'n is %d' % (candidate)
print 'Sum of log primes is %e' % (total)
print 'Ratio is %e' % (ratio)
break
Shewlayce
1 year ago