[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
From:
Anonymous( )Anonymous This community only allows commenting by members. You may comment here if you're a member of intro_to_cs.
OpenID (will be screened if not on Access List)
Identity URL: 
User (will be screened if not on Access List)
Account name:
Password:
If you don't have an account you can create one now.
Subject:
HTML doesn't work in the subject.

Message:

 
Links will be displayed as unclickable URLs to help prevent spam.

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 Sep. 25th, 2017 06:13 am
Powered by Dreamwidth Studios