aranthe (
aranthe) wrote in
intro_to_cs2010-03-25 01:05 pm
![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
![[community profile]](https://www.dreamwidth.org/img/silk/identity/community.png)
Entry tags:
PS1: Problem 2 » Solution
PS 1: Problem 2
# Import math module. from math import * # Enter the upper limit. n = int(raw_input( 'Compute for primes between 2 and this number: ')) # Initialize state variables. primes = [2] count = 1 log_sum = 0 limit = n - 1 # Do this because we're incrementing by 2. # Do this until we reach the limit. while count < limit: # Increment counter by 2. (Eliminates all divisible by 2.) count += 2 # Set prime switch true. is_prime = True # Loop through the testing slice. for prime in primes: # Check to see if count is prime. if count % prime == 0: # Not a prime, set switch to false. is_prime = False # Don't waste any more time on this number. break # Check for testing limit. if prime**2 > count: break # Check the switch; if it's still true... if is_prime: #...count is prime. Add it to the primes array. primes.append(count) # Loop through the primes and add up the logs. for prime in primes: log_sum += log(prime) # Compute the ratio of the sum to the limit ratio = log_sum / limit length = len(primes) # print print 'The upper limit (n) is:', n print 'Computed for', length, 'primes.' print 'The sum of the logarithms of these primes is', log_sum print 'The ratio of the sum to the limit is:', ratio