[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
This community only allows commenting by members. You may comment here if you're a member of intro_to_cs.
(will be screened if not on Access List)
(will be screened if not on Access List)
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

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. 9th, 2025 12:34 am
Powered by Dreamwidth Studios