MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 2, HW 1
## Problem Set 1
## Problem 1 =====================================
## Initializing Variables
potentialP = 3 # Potential Prime number being tested
countofP = 1 # Number of Primes generated (starts
# at 1 because 2 is assumed to be known)
testdivisor = 3 # The integer by which the potential prime is
# divided by
## Prime Generating Program
while countofP < 1000: # Searches for primes so long as the required number
# of primes hasn't been reached
while potentialP%testdivisor != 0: #Finds the first divisor for the current potentialP
testdivisor += 2
if potentialP == testdivisor: # If the first generated divsor is equal to
# potentialP, then it is a prime. In that case, print
# potentialP and increase the count of primes by 1
print potentialP
countofP += 1
testdivisor = 3 # Reset testdivisor
potentialP += 2 # Generate next potential prime number
from math import *
## Problem 2 =====================================
## Initializing Variables
potentialP = 3 # Potential Prime number being tested
countofP = 1 # Number of Primes generated (starts
maxnumofP = 2000 # Desired Number of Primes to be generated
testdivisor = 3 # The integer by which the potential prime is
# divided by
SumOfLogs = log(2) # Sum of the natural log of primes generated.
# Starts at log(2) because 2 is not generated
## Program summing the natural logarithms of all primes
## up to maxnumofP
while countofP < maxnumofP: # Searches for primes so long as the requested number
# of primes hasn't been reached
while potentialP%testdivisor != 0: #Finds the first divisor for the current potentialP
testdivisor += 2
if potentialP == testdivisor: # If the first found divsor found is equal to
# potentialP, then it is a prime. In that case,
# add the log of the prime to SumOfLogs and
# increase the count of primes by 1
SumOfLogs += log(potentialP)
countofP += 1
testdivisor = 3 # Resets testdivisor
potentialP += 2 # Generates next potential prime number
print SumOfLogs
print maxnumofP
print SumOfLogs/maxnumofP
Typus
11 months ago