[personal profile] aranthe posting in [community profile] intro_to_cs

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

Profile

Introduction to Computer Science

July 2010

S M T W T F S
    123
45678910
11121314151617
18192021222324
2526272829 3031

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 7th, 2025 10:34 am
Powered by Dreamwidth Studios