|
MIT OpenCourseWare 6.00 Introduction to Computer Science and ProgrammingClass length: 13 weeks. Start anytime. Creator: duallain Status: Under Construction |
|
Assignment 1Homework Submissions (29 total):Second program for MIT OCW course#problem one prime_canidate = 3 prime_counter = 1 #2 already counted prime_test = [2] def isprime(n): for x in prime_test: if n % x == 0: return False return True while ( prime_counter < 1000 ): if isprime(prime_canidate) == True: prime_test.append(prime_canidate) prime_counter += 1 prime_canidate += 2 else: prime_canidate += 1 print prime_canidate - 2 #problem 2 from math import * log_sum=0 n = 2 for x in prime_test: if x <= n: log_sum = log_sum + log(x) print "the sum of log(prime) where prime <= n = ", log_sum print "n = ", n print "The ratio of log_sum/n = ", log_sum/nPermalink ... #Problem 1
number_of_primes = 0
candidate = 0
test = 0
remainder = 0
while (1):
candidate = candidate + 1
#test primality
#1 if prime, 0 if not
for test in range(candidate):
remainder = (candidate)%(test + 1)
if remainder == 0 and (test + 1) <> 1 and (test + 1) <> candidate:
#not prime
break
if (test + 1) == candidate and candidate <> 1:
number_of_primes = number_of_primes + 1
if number_of_primes == 1000:
print 'The %dth prime is %d' % (number_of_primes, candidate)
break
#Problem 2
from math import *
number_of_primes = 0
candidate = 0
test = 0
remainder = 0
total = 0
ratio = 0
while (1):
candidate = candidate + 1
#test primality
#1 if prime, 0 if not
for test in range(candidate):
remainder = (candidate)%(test + 1)
if remainder == 0 and (test + 1) <> 1 and (test + 1) <> candidate:
#not prime
break
if (test + 1) == candidate and candidate <> 1:
#prime
total = total + log(candidate)
number_of_primes = number_of_primes + 1
if candidate == 1000:
ratio = total / candidate
print 'n is %d' % (candidate)
print 'Sum of log primes is %e' % (total)
print 'Ratio is %e' % (ratio)
break
Permalink
Comments:what does '' do? Could you (or someone else) maybe elaborate on the behavior or thought process of the for loop you use to test primality? can you explain the 'while (1):' and the ' 1' parts of the code. I've never seen that kind of syntax in python and am curious as to what it means. pset1 ## question #1
import math
first_prime = 2
max_prime_count = 1000
count = 1
next_prime = first_prime + 1
count = count + 1
while (count < max_prime_count):
next_prime = next_prime + 2
stop_value = math.sqrt(next_prime)
is_prime = True
value = 2
#Check if the "prime" is really prime by dividing it by
# all integers up to its sqrt and looking for remainders
while (value <= stop_value):
if (next_prime%value == 0):
is_prime = False
value = stop_value+1
else: value = value + 1
#increment counter if it is prime
if (is_prime):
count = count + 1
#print count, ': ', next_prime
print '1000th prime is ' + str(next_prime)
## question #2
from math import *
first_prime = 2
max_prime_count = raw_input('How many primes: ')
count = 1
log_sum = log(first_prime)
next_prime = first_prime + 1
count = count + 1
log_sum = log_sum + log(next_prime)
while (count < int(max_prime_count)):
next_prime = next_prime + 2
stop_value = sqrt(next_prime)
is_prime = True
value = 2
#Check if the "prime" is really prime by dividing it by
# all integers up to its sqrt and looking for remainders
while (value <= stop_value):
if (next_prime%value == 0):
is_prime = False
value = stop_value+1
else: value = value + 1
#increment counter if it is prime, print out the sum of logs,
# and the ratio of the latest prime to it
if (is_prime):
log_sum = log_sum + log(next_prime)
count = count + 1
ratio = next_prime/log_sum
print count, ': ', next_prime, log_sum, ratio
Permalink
No comments. Sign up or log in to comment I had trouble submitting this for some reason. Also, i'd like to say that I'm rather proud of myself after this assignment (although my solutions appear mroe verbose than others that have been submitted): I haven't done math in awhile and I was concerned that I didn't have the necessary math on hand to fulfill this assignment. I had no idea how powerful recursion is. primes = [2]
## factor(n) returns a list of the factors of n
def factor(n):
factors = []
factorcandidate = n + 1
while factorcandidate > 3:
factorcandidate = factorcandidate - 1
if n%factorcandidate == 0:
factors.append(factorcandidate)
return factors
## findprimes(x) takes a list (of factors) and identifes which
## elements in the list are primes, then appends them to the list
## 'primes' if they are not already elements.
def findprimes(factors):
for f in factors:
if f not in primes:
factorable = 0
for p in primes:
if f%p == 0:
factorable = factorable + 1
if factorable == 0:
primes.append(f)
primes.sort()
## nprime(n) returns the nth-prime number. In the process, all the
## primes from 1 to nprime(n) are generated and stored in the list
## 'primes' in ascending order.
def nprime(n):
counter = 1
if len(primes) >= n:
return primes[n-1]
else:
while len(primes) < n:
counter = counter + 2
findprimes(factor(counter))
return primes[n-1]
#PROBLEM 2
from math import *
#Generatest the primes up to a number n. Includes the number n if n is prime.
def generateprimes(n):
counter = 2
if n < counter:
return primes
else:
while counter <= n - 1:
counter = counter + 1
findprimes(factor(counter))
return primes
## returns a list of primes up to (and including) a number n.
def smallerprimes(n):
generateprimes(n)
listprimes = []
for x in primes:
if x <= n:
listprimes.append(x)
return listprimes
## takes a number n and feeds it to smallerprimes() to generate the list of primes to sum for building the ratio.
def primeratio(n):
listofprimes = smallerprimes(n)
logs = []
for prime in listofprimes:
logs.append(log(prime))
logofprimes = sum(logs)
ratio = logofprimes/n
print "Sum of logs of primes = ", logofprimes
print "n = ", n
print "ratio of logs/n = ", ratio
Permalink
Comments:in retrospect, my solution to this problem was way more complicated than it needed to be. I don't understand iterating over all the factors and all the possible numbers for every prime candidate. Doesn't it waste time doing tests on 4, 6, 9, and 64... when you already know 2 and 3 are factors and, therefore the candidate isn't prime? #problem 1
isprime = [2] #initializes the list of primes
i = 3
while len(isprime) < 1000: #continue until 1000th prime
prime = True #assume i is prime
for j in isprime: #compare it to the list
if i%j == 0: #to see if it divides evenly
prime = False
else:
pass
if prime:
isprime.append(i) #if it doesn't, add it to the list
i += 1
print isprime[-1]
#problem 2
isprime = [2]
for i in range (3, n, 2):
prime = True
for j in isprime:
if i%j == 0:
prime = False
else:
pass
if prime:
isprime.append(i) #like above, collect all the primes
j = 0
for prime in isprime:
j = j + log(prime) #calculate the log of the sum of 'em
print 'The sum of the log of primes <= n is:',j
print 'n is:', n
print 'The ratio is:',j/n
Permalink
No comments. Sign up or log in to comment I enjoyed this - tried to write a solution that was easy to read and understand. I made it a bit more flexible to test for any number rather than just 1000. #Problem Set 1a ( Problem 1 )
primeswanted = int(input("This program will find the nth prime. \nPlease enter n:"))
if primeswanted <=0:
print "n must be >= 1"
else:
lastprime = 2
primesfound = 1
primecandidate = lastprime + 1
while primesfound < primeswanted: # range of search
possibly_prime = True
for divisor in range(2, primecandidate, 1): # testing
if possibly_prime:
possibly_prime = ((primecandidate % divisor) != 0) # testing continued
if possibly_prime:
lastprime = primecandidate # moving the marker
primesfound = primesfound + 1
primecandidate = primecandidate + 1
print "The nth prime is:", lastprime
#Problem Set 1b ( Problem 2 )
from math import *
primeswanted = int(input("This program will sum logs of primes through the nth and give the ratio between the sum and n.\nPlease enter n:"))
if primeswanted <=0:
print "n must be >= 1"
else:
lastprime = 2
primelogs = log(2) # giving initial value for primelogs
primesfound = 1
primecandidate = lastprime + 1
while primesfound < primeswanted:
possibly_prime = True
for divisor in range(2, primecandidate, 1): # searching
if possibly_prime:
possibly_prime = ((primecandidate % divisor) != 0) # testing
if possibly_prime:
lastprime = primecandidate # moving the marker
primesfound = primesfound + 1
newprimelog = log(primecandidate)
primelogs = primelogs + newprimelog # summing the logs of primes
primecandidate = primecandidate + 1
print "The sum of the logs of the primes is:", primelogs
print "The number of primes was (or n equals):", primeswanted
print "The ratio between the sum of the logs of primes and n is:", primelogs / primeswanted
Permalink
No comments. Sign up or log in to comment # Problem Set 1
# Name: Bertrand Croq
# Time: 00:10
from math import log
def problem1(count=1000):
primes = []
n = 1
print 1 # 1 is prime
while len(primes) < count:
n += 1
for p in primes:
if not (n % p):
break
else:
print n
primes.append(n)
def problem2(n):
primes = []
sum = 0
def show():
print sum, current, sum / current
for current in xrange(2, n+1):
for p in primes:
if not (current % p):
break
else:
sum += log(current)
primes.append(current)
#show()
show()
Permalink
No comments. Sign up or log in to comment # Problem Set 1
# Name: Kirill Klenov
# Time: 0:29
def is_prime(n):
if n == 0 or n == 1: return True
for number in range(2,n - 1):
if not n % number: return False
return True
def get_primes(n = 1000):
return [n for n in range(n) if is_prime(n)]
# Problem 1
for n in get_primes(): print n
from math import log
def problem_2(n):
primes = get_primes(n)
_sum = sum(map(lambda x: log(x), primes[2:]))
return _sum, n, _sum / n
# Problem 2
print problem_2(400)
print problem_2(1400)
Permalink
No comments. Sign up or log in to comment # Problem Set 1 & 2 # Name: Jeroen Pelgrims # Collaborators: # Time: 0:15 # def isPrime(x): if x <= 1 or x == 4: return False for i in range(2, int(x/2)): if x%i==0: return False return True def gOdds(): i=2 while True: if i%2 != 0: yield i i += 1 def gPrime(): yield 2 odds = gOdds() i = odds.next() while True: if isPrime(i): yield i i = odds.next() gPrimeI = gPrime() #Problem 1 print [gPrimeI.next() for x in range(1000)][-1] #Problem 2 gPrimeI = gPrime() from math import log valuesOfN = [10**x for x in range(0, 5)] #the first 10000 primes primes = [gPrimeI.next() for x in range(max(valuesOfN))] for n in valuesOfN: logSum = sum([log(primes[x]) for x in range(n) if primes[x] < n]) print "%7d %5d %6.2f" % (logSum, n, logSum/n)Permalink No comments. Sign up or log in to comment I haven't practiced logarithms in about 12 years and just had to google it to find out what it was. As to the fact that I'm not actually paying any money for this course, I've decided to not do problem 2. In its place I'd like to give you this text-face in hopes of a good grade. Thank you. d[-_-]b #!
# Problem Set 1 - Problem 1
# Name: Gautama Shakyamuni
# Collaborators:
# Time: 00:45:00
#
def FindNthPrime(n):
primes = [2]
odd = 3
if n <= 0:
return "NIL"
elif n == 1:
return primes[0]
else:
while len(primes) < n:
for k in range(2,odd):
if odd % k == 0:
odd += 2
break
else:
primes.append(odd)
odd += 2
return "The Prime number you wanted is: " + str(primes[len(primes)-1])
Permalink
No comments. Sign up or log in to comment # Edit: apparently the syntax highlighter doesn't like triple-quoted strings,
# as used for documentation; converted them to code comments.
from math import *
def is_prime(n):
# Simple prime check with a few early checks to save from the full check.
if n % 2 == 0:
return False
sqroot = sqrt(n)
if int(sqroot) == sqroot: # Does the square root have a fractional part?
return False
test = 3
while test <= sqroot:
if n % test == 0:
return False
test += 2
return True
def next_prime(n):
# Find the next prime greater than n (n doesn't have to be prime!)
check = n
if n % 2 == 0: # Is n even?
check += 1
else:
check += 2
while not is_prime(check):
check += 2
return check
def thousandth_prime(n=1000):
# Get the thousandth prime.
count = 1 # 2 is prime
last = 2
while count < n:
count += 1
last = next_prime(last)
return last
def sumlogs(n):
# Sum of primes 2 through n; not ideal, always computes one unused prime.
# One solution would be to use Eratosthenes' sieve to first compute all
# needed primes. Tradeoff there is space versus CPU use.
last = 1
sumlg = log(2)
while last <= n:
sumlg += log(last)
last = next_prime(last)
return sumlg
# Part 1
print(thousandth_prime())
# Part 2
n = int(raw_input("Enter the upper limit for primes: "))
sumlg = sumlogs(n)
print(sumlg)
print(n)
print(sumlg/n)
Permalink
Comments:You have to be careful when comparing the fractional part of the square root: sqrt(199599235**2 + 1) == int(199599235) returns as true. sqrt(199599235**2 + 1) == int(199599235) I didn't consider running with large inputs like that, but I'll keep it in mind. Probably would need to implement a slower, but (hopefully) more dependable method if it were used for large integers, such as Newton's Method. Thanks.
import math
def getPrime(num):
i = 1
j = 3;
primes = [1,3]
while i < num:
k = 2;
while k < math.sqrt(j):
if j%k == 0:
break
k = k + 1
if k >= math.sqrt(j):
i = i + 1;
j = j + 2;
primes.append(j-2)
return primes;
p = getPrime(1000)
print p[len(p)-1]
for i in range(2,100):
primes = getPrime(i)
k = 0
for i in primes:
k = k + math.log(i)
print " Number : {0} Sum of logs : {1} ratio : {2}".format(i,k,i/k)
Permalink
Please provide some feedback? In order to "expedite" the prime calculations, I only try to divide them by odd numbers, and stop at values <= the square root of the candidate. What other numbers can I eliminate? ##Part 1
from math import *
list_of_candidates = range(5, 10000, 2) ##create a list with odd numbers
prime_numbers = [] #this is going to be my collection of generated prime numbers
for candidate in list_of_candidates: #go through all odd numbers
if len(prime_numbers) == 1000: break #test the # of prime numbers found
divisor = 3 #this is the first denominator we're going to start with
while divisor < candidate and divisor <= sqrt(candidate): #test denominators less than the candidate, and <= its square root
if candidate % divisor == 0: break #this must not be a prime number
elif candidate % divisor > 0: #the denimator doesn't go into the candidate evenly
divisor = divisor + 2 #increment the denominator, but stay with odd denominators
else: prime_numbers.append(candidate) #reaching this statement requires the number to be prime
prime_numbers.insert(0, 2) #adding the missing prime 2 to our final list
prime_numbers.insert(1, 3) #adding the missing prime 3 to our final list
print "The 1000's prime number is ", prime_numbers[999] #Final output to user
###########PART 2 (continuation of part 1)
numberN = int(raw_input(["Enter a number less than ", prime_numbers[999]])) #ask to use a number less than the biggest prime stored
i = 0 #define our itterator
sum_of_logs = 0 #set the initial sum
while int(prime_numbers[i]) < numberN: #test if we've reached the user number
sum_of_logs = sum_of_logs + log(prime_numbers[i]) #keep adding until we reach the user specified number
i = i + 1 #increment itterator
print "your number: ", numberN, "\nthe sum of all primes below is", sum_of_logs, "\ntheir ratio is", sum_of_logs/numberN
Permalink
Comments:One I did implement was to check if the square root of the candidate has no fractional part. I was computing the square root anyway (to stop the manual check once it is reached), so that made it easy enough to check. A couple I didn't attempt to implement were:
Thank you! For 1,2: Did you eliminate the numbers when generating your initial candidates, or when creating your list of primes? I would probably eliminate them when creating the list of primes in order to leave the candidate generation as simple as possible. It keeps the flow of generation, then simple checks, then the full, grind-it-out check. # Problem Set 1
# Name: jspash
# Collaborators: me
# Time: 1:00
#
from math import *
# A prime number is only divisible by 1 and itself
# That is the law. And the law is good. All hail the law.
def is_prime(number):
for i in range(1,number):
if number % i == 0:
if number != i and i != 1:
return False
return True
# Initialise the count to 1 because we've already "found" 2 to be prime
primes_found = 1
# Beginning with 3 get all odd numbers to 100,000
# because the hint "Generate all (odd) integers > 1 as candidates to be prime"
# is just plain silly and could take a while
list_o_primes = range(3, 10000, 2)
prime_list = [2]
for test_me in list_o_primes:
if is_prime(test_me):
primes_found = primes_found + 1
prime_list.append(test_me)
# Write a program that computes the sum of the logarithms of all the primes from 2 to some number n,
# and print out the sum of the logs of the primes, the number n, and the ratio of these two quantities.
# Test this for different values of n.
your_number = 12
int(raw_input('Enter number for test:'))
sum_of_logs = 0
for tmp in list_o_primes:
if tmp > your_number:
break
sum_of_logs = sum_of_logs + log(tmp)
print 'Your number:', your_number
print 'Sum of logs:', sum_of_logs
print 'Ratio:', sum_of_logs / your_number
Permalink
No comments. Sign up or log in to comment I've tried to do this problem set sticking within the confines of what we know in the class up to this point. #Problem 1 Computing Prime Numbers
#jayd
from math import sqrt
primeNumbers=[2,]
n=1
#Loop till 1000 primes are generated
while len(primeNumbers) <1000:
n+=2
nFactors = 0
# Loop through all divisors less than the sqrt of n
for divisor in range(2,int(sqrt(n))+1):
remainder = n % divisor
if remainder == 0:
nFactors += 1
if nFactors == 0:
print "Prime Found:",n
primeNumbers.append(n)
print "The 1000th prime is:", primeNumbers[999]
#Problem 1 Part 2 Sum of Log(prime)
#jayd
from math import *
def productOfPrimes(max):
primeNumbers=[2,]
n=1
#Generate Primes up to a max value
while primeNumbers[-1] <= max:
n+=2
isPrime=True
# Loop through all divisors less than the sqrt of n (rounded to the nearest int)
# If a factor is found set isPrime to false and break
maximum=sqrt(n)
for divisor in primeNumbers:
if divisor > maximum:
break
if n % divisor == 0:
isPrime=False
break
if isPrime == True:
if n < max:
primeNumbers.append(n)
else: break
sumOfPrimes=0
i=0
for prime in primeNumbers:
sumOfPrimes+=log(prime)
print "Sum of Primes:",sumOfPrimes
ratio=sumOfPrimes/max
return ratio
ratio = productOfPrimes(97)
print "Ratio:",ratio
Permalink
No comments. Sign up or log in to comment #Problem Set 1a
#Name:Saouka
#Collaborators: None
#Time: 1:30
global chkprime
chkprime = 12
CurrentNumber = 3
PrimesRequested = 10000 #Ignoring 2 as a prime in the algorithm, accounting for that here.
def checkprime(CurrentNumber):
x = 2
while x < CurrentNumber:
if CurrentNumber%x == 0:
global chkprime
chkprime=0
return CurrentNumber,chkprime
x=x+1
global chkprime
chkprime = 1
print CurrentNumber
return CurrentNumber,chkprime
while 0 < PrimesRequested:
checkprime(CurrentNumber)
if chkprime == 1:
PrimesRequested = PrimesRequested -1
CurrentNumber = CurrentNumber +2
else:
CurrentNumber = CurrentNumber +2
print CurrentNumber -2
#Problem Set 1b
#Name:Saouka
#Collaborators: None
#Time: 1:30
from math import *
global chkprime
chkprime = 12
CurrentNumber = 3
Numbertotal = input('What is N?')
global sumoflog
sumoflog = log(2)
def checkprime(CurrentNumber):
x = 2
while x < CurrentNumber:
if CurrentNumber%x == 0:
global chkprime
chkprime=0
return CurrentNumber,chkprime
x=x+1
global chkprime
chkprime = 1
global sumoflog
sumoflog = sumoflog + log(CurrentNumber)
return CurrentNumber,chkprime
while CurrentNumber < (Numbertotal):
checkprime(CurrentNumber)
CurrentNumber = CurrentNumber +2
print ' The Sum of Logs is', sumoflog
print 'N is', Numbertotal
print 'The Ratio is', sumoflog/Numbertotal
Permalink
I thought I would post this even though I did it a few weeks ago. Just in case it helps someone who is out there looking. Note that when determining if a number n has factors greater than 1, one of the factors from each pair will always be less than the square root of n. There are far more efficient ways to limit the search for factors, but this was good enough for me. import math
def sum_prime_logs(input):
sum_of_prime_logs = 0
odd_number = 3 #to calculate which numbers less than input are primes, we only need worry about odd numbers
while odd_number <= input: #for each odd number less than input, work out if it is a prime
is_prime = True #assume it's a prime
for i in range(3, (int(math.sqrt(odd_number)) + 1)): #it's not a prime if it is perfectly divisible by any number between 3 and its (square root + 1) (this saves time, one factor will always be below the square root)
if odd_number % i == 0:
is_prime = False
if is_prime == True:
sum_of_prime_logs = sum_of_prime_logs + math.log(odd_number)
odd_number += 2
print 'the sum of the logarithms of the primes less than', input, 'is', sum_of_prime_logs
print 'the ratio of that logarithmic sum dividied', input, 'is', sum_of_prime_logs/input, 'which should approach 1 for larger values of input'
test_set = [100,1000,10000,100000]#,1000000] - takes a long time
for x in test_set:
sum_prime_logs(x)
Permalink
No comments. Sign up or log in to comment # Problem Set 1a
# Name: danmanuk
# Collaborators: n/a
# Time: 00:30
from math import *
# PROBLEM 1 --> Write a program that computes and prints the 1000th prime number.
candidates = range(3,10000,2)
prime = [2]
# We didn't create first prime --> 2
counter = 1
for candidate in candidates:
upper = int(sqrt(candidate))
for num in range(2,upper):
if candidate % num == 0:
break
else:
# found a prime --> increment counter
counter += 1
prime.append(candidate)
if counter == 1000:
break
print 'The 1000th prime number is %s.' % (prime[-1])
# Problem Set 1b
# Name: danmanuk
# Collaborators: n/a
from math import *
# PROBLEM 2
prime = [2] # --> first prime is 2
n = int(raw_input('Enter a value for n:'))
candidate = 3
counter = 1
while candidate < n:
# only need to test for prime upto sqrt(candidate)
upper = int(sqrt(candidate))
for num in range(2,upper):
if candidate % num == 0:
break
else:
# found a prime --> increment counter
counter += 1
prime.append(candidate)
candidate += 2
logs_of_primes = map(lambda x:math.log(x),prime)
sum_of_logs = reduce(lambda x, y: x + y, logs_of_primes)
print 'The sum of the logs of the primes is: %0.3f.' % (sum_of_logs)
print 'The number of primes is: %s' % (n)
print 'The ratio of the above quantities is: %0.3f.' % (sum_of_logs/n)
Permalink
No comments. Sign up or log in to comment ############
#Problem 1:#
############
from math import *
n = 1
primes = 1 #the 1 prime already "found" is 2
while (primes != 1000):
n += 2 #increments by 2 (only odd nums considered)
for div in range(3, int(sqrt(n)+1)):
rem = n%div
if rem == 0: break
else: primes += 1
else: print n
############
#Problem 2:#
############
def genPrimes(lim):
yield 2
for n in xrange(3,lim,2):
for div in xrange(3, int(sqrt(n)+1)):
rem = n % div
if rem == 0: break
else: yield n
def sumlog(N):
total = sum(log(n) for n in N)
return total
n = int(raw_input('Give me a number: '))
tot = sumlog(genPrimes(n))
ratio = float(tot)/n
print 'Your number is',n
print 'The sum of the logs of the primes from 2 to',n,'is',tot
print 'The ratio is',ratio
Permalink
No comments. Sign up or log in to comment # Problem Set 1 a
# Name: Mark Calderwood
primecount = 2
candidate = 5
divsor = 2
isprime = 1
while primecount < 1000:
divisor = (candidate - 1)/2
# start with the candidate -1 (to make it even) and then divide this
#by two, (a numbers biggest factor is always the one that goes
#into it twice)
while divisor > 2:
# we know it isn't even so we need to check if it is divisible by
# everything bigger than 2
if candidate % divisor == 0:
isprime = 0
break
else:
isprime = 1
divisor -= 1
if isprime == 1:
#print candidate ("scaffolding" code)
primecount += 1
candidate += 2
else:
candidate += 2
print candidate - 2 # remove the last increment before printing
# Problem Set 1 b
# Name: Mark Calderwood
from math import *
primecount = 2
candidate = 5
divsor = 2
isprime = 1
sumoflogs = log(2) + log(3)
while primecount < 1000:
divisor = (candidate - 1)/2
# start with the candidate -1 (to make it even) and then divide this
# by two, (a numbers biggest factor is always the one that goes
#into it twice)
while divisor > 2:
# we know it isn't even so we need to check if it is divisible by
# everything bigger than 2
if candidate % divisor == 0:
isprime = 0
break
else:
isprime = 1
divisor -= 1
if isprime == 1:
print candidate
sumoflogs = sumoflogs + log(candidate)
print sumoflogs
print candidate/sumoflogs
primecount += 1
candidate += 2
else:
candidate += 2
Permalink
No comments. Sign up or log in to comment # problemset 1
# Jyen
# Time 30 min
#problem 1
n = 1000
primescount = 1
candidatenumber = 3
while primescount < n: #evaluate until Nth prime found
test = 3
if candidatenumber%2 > 0:
while candidatenumber%test>0 and test < candidatenumber/2:
test = test + 1
if candidatenumber%test>0 or candidatenumber == test:
# print candidatenumber
primescount = primescount + 1
candidatenumber = candidatenumber + 1
print "Part 1: The 1,000th prime is ", (candidatenumber - 1)
# problem 2
from math import *
stringinput = raw_input ("How many numbers? ")
n = int(stringinput)
sumoflogs = 0
primescount = 1
candidatenumber = 3
print "Part 2:"
while primescount < n:
test = 3
if candidatenumber%2 > 0:
while candidatenumber%test>0 and test < candidatenumber/2:
test = test + 1
if candidatenumber%test>0 or candidatenumber == test:
sumoflogs = sumoflogs + log(candidatenumber)
#print sumoflogs
primescount = primescount + 1
candidatenumber = candidatenumber + 1
print "Sum of the logs of the primes = ", sumoflogs
print "N = ", n
print "Ration sumoflogs/N =", (sumoflogs/n)
Permalink
No comments. Sign up or log in to comment #Problem Set #1
#Name: Alex Wan
#Collaborators: The Python tutorial on for statements, located here: http://docs.python.org/tutorial/controlflow.html#for-statements
#Time: 2:00
#Find the 1000th prime number. This looks like it'll be really hard.
primecandidate = 3
finalprime = int(input('Enter the Nth prime number you want to find:')) #Input 1000.
primecount = 1
while (primecount < finalprime):
for divisor in range(2, primecandidate):
if primecandidate % divisor == 0:
primecandidate = primecandidate + 1
break
else:
print primecandidate, 'is a prime number'
primecandidate = primecandidate + 1
primecount = primecount + 1
print primecandidate - 1, 'is the', finalprime, 'th prime number.'
#In addition, write a program that computes the sum of the logarithms of all the primes from 2 to N.
#Print out this sum, the number N, and the ratio between the sum and N (sum/N)
from math import *
primecandidate = 3
finalprime = int(input('Enter the Nth prime number you want to find:')) #This is N.
primecount = 1
logsum = log(2)
while (primecount < finalprime):
for divisor in range(2, primecandidate):
if primecandidate % divisor == 0:
primecandidate = primecandidate + 1
break
else:
print primecandidate, 'is a prime number'
logsum = logsum + log(primecandidate)
primecandidate = primecandidate + 1
primecount = primecount + 1
print primecandidate - 1, 'is the', finalprime, 'th prime number.'
print 'The sum of all the logarithms of all the prime numbers between 2 and', primecandidate - 1, 'is', logsum
print 'The ratio between', logsum, 'and', primecandidate - 1, 'is', (logsum/(primecandidate - 1))
Permalink
No comments. Sign up or log in to comment Problem sets 1a and 1b def isprime(n):
'''Check whether integer n is a prime number'''
# First we make sure n is a positive integer
n = abs(int(n))
# Zero and one are not primes
if n < 2:
return False
# Two is the only even prime
if n == 2:
return True
# All other even numbers are not primes
# & is the bitwise AND operator, it tells us whether the number is even
if not n & 1:
return False
# Start with three and go up to square root of n for all odd numbers
for x in range (3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
# Start our index at one because we increment it in the if statement
index=1
testnum=3
while index < 1000:
if isprime(testnum) == True:
index=index+1
if index == 1000:
# Using sys.stdout.write because python is retarded and keeps putting
# spaces after the index and before "th"
import sys
sys.stdout.write(testnum)
sys.stdout.write(" is the ")
sys.stdout.write(index)
sys.stdout.write("th prime number.")
testnum=testnum+2
## Problem set 1b
from math import *
# We'll recycle our handy "isprime" function from part A of the homework
def isprime(n):
'''Check whether integer n is a prime number'''
# First we make sure n is a positive integer
n = abs(int(n))
# Zero and one are not primes
if n < 2:
return False
# Two is the only even prime
if n == 2:
return True
# All other even numbers are not primes
# & is the bitwise AND operator, it tells us whether the number is even
if not n & 1:
return False
# Start with three and go up to square root of n for all odd numbers
for x in range (3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
n=100000
testnum=3
# We'll set log(2) as the initial value of logsum, since two is the only even
# prime number.
logsum=log(2)
while testnum < n:
if isprime(testnum) == True:
logsum=logsum+log(testnum)
testnum=testnum+2
print "The sum of the logarithms of all primes below",(n),"is",(logsum)
print "The ratio of logsum to n is",(logsum)/(testnum)
Permalink
No comments. Sign up or log in to comment #Problem Set 1a ( Problem 1 )
step = 2
current_int = 1
prime_cnt = 0
while prime_cnt < 1000:
is_prime = True
test_int = 2
while test_int**2 <= current_int:
if current_int % test_int == 0:
is_prime = False
break
else:
is_prime = True
test_int += 1
if is_prime:
prime_cnt += + 1
print prime_cnt, ' ', current_int
current_int = current_int + step
#Problem Set 1b ( Problem 2 )
from math import *
step = 2
current_int = 1
stop_int = 1000
sum_log = 0
while current_int < stop_int:
is_prime = True
test_int = 2
while test_int**2 <= current_int:
if current_int % test_int == 0:
is_prime = False
break
else:
is_prime = True
test_int += 1
if is_prime:
sum_log += log(current_int)
current_int = current_int + step
print 'Sum of log: ', sum_log
print 'Value n: ', stop_int
print 'Raito: ', sum_log/current_intlast_name
Permalink
No comments. Sign up or log in to comment Computing prime numbers, product of primes #Problem Set 1 (PART I)
#Name Joe Li
#Time 4:30
#
x=3 # candidate
d=2 # divisor
count=1 # the number of prime has been found
while count!=1000: # do the following utill the 1000th prime has been found
while x%d==0: # while the remainder is zero, which means x is not a prime
x+=1 # test next x
d=2 # reset divisor
else: # while the remainder is not zero
if d==x-1: # and the divisor is the last one to test with, prime comfirmed
count+=1 # count
x+=1 # test next x
d=2 # reset divisor
else: # and the divisor is not the last one to test
d+=1 # test with next divisor
else: # 1000 primes have been found
print x-1 # print the last one (the 1000th prime)
#Problem Set 1 (PART II)
#Name Joe Li
#Time 0:10
#
from math import *
x=3 # candidate
d=2 # divisor
n=1 # the number of prime has been found
s=log(2) # the sum of log
while n!=1000: # do the following utill the nth prime has been found
while x%d==0: # while the remainder is zero, which means x is not a prime
x+=1 # test next x
d=2 # reset divisor
else: # while the remainder is not zero
if d==x-1: # and the divisor is the last one to test with, prime comfirmed
n+=1 # count
s+=log(x) # add to sum
x+=1 # test next x
d=2 # reset divisor
else: # and the divisor is not the last one to test
d+=1 # test with next divisor
else: # all the log of prime less than n have been added to sum
print s,x-1,s/(x-1) # print the sum, n, ratio
Permalink
No comments. Sign up or log in to comment ps1a Name: Peragon Time: 04:30:00 Collaborators: none I had a bunch of trouble on the first part, and had to resort to looking up other student's solutions to adapt them for myself. Thank you Duallain! The second part only took about thirty minutes. # This my solution to problem 1
number = int(raw_input('What prime would you like to find? ')
list_of_primes = [2]
number_of_primes = 1
testing_number = 3
def primality(n):
for a in list_of_primes:
if n % a == 0:
return False
return True
while number_of_primes <= number-1:
if primality(testing_number) == True:
list_of_primes.append(testing_number)
number_of_primes += 1
testing_number += 2
else:
testing_number += 2
# Here is problem 2
from math import *
while continuity == False:
def generate_primelist(z):
list_of_primes = [2]
number_of_primes = 1
testing_number = 3
def primality(n):
for a in list_of_primes:
if n % a == 0:
return False
return True
while list_of_primes[-1] != z:
if primality(testing_number) == True:
list_of_primes.append(testing_number)
number_of_primes += 1
testing_number += 2
else:
testing_number += 2
return list_of_primes
def take_log(list_of_primes):
sum_of_logs = 0
for a in list_of_primes:
sum_of_logs += log(a)
return sum_of_logs
prime = int(raw_input('Please enter a prime to test: ')
prime_list_z = generate_primelist(prime)
prime_log = take_log(prime_list_z)
print 'Your number is: ', prime
print 'The natural logarithm of all the primes up to your number is : ', prime_log
print 'The ratio of these two quantities is: ', prime_log/n, '\n'
continuity = 'Do you wish to continue? y/n: '
if continuity == y:
continuity == True
else:
continuity == False
Permalink
No comments. Sign up or log in to comment #Problem Set 1
#Name: chip
import math
N = 1000
log_sum = math.log(2)
print(2)
for counter in range(3, N, 2):
prime = True
for j in range(3, N - 1, 2):
if counter % j == 0 and counter != j:
prime = False
break
if prime:
log_sum += math.log(counter)
print(counter)
counter += 2;
print("Sum of logs is: ", log_sum)
print("N equals to: ", N)
print("Ration is: ", log_sum / N)
Permalink
No comments. Sign up or log in to comment # Problem 1
primes = [2] # The first of the Primes.
x = 3 # First number to test.
while len(primes) < 1000: # Check that we still haven't found the 1000th prime!
isprime = True # Assume the number IS prime. Test against it.
for prime in primes: # For all the primes;
if (x%prime) == 0: # check to see if the number is divisable by a prime. If it is, set isprime to False.
isprime = False
if isprime:
primes.append(x)
x = x+2
print "And the 1000th Prime is... *drumroll*", primes[-1]
# Problem 2
print "And now for some Prime logging!"
from math import *
someLog = 0
n = input("So, what should our value of 'n' be?")
for prime in primes:
if prime <= n:
someLog = someLog + log(x)
print "Sum of the Prime logs: ", someLog
print "Wait, what was 'n' anyway? ", n
print "And how are they related now? ", someLog/n
Permalink
No comments. Sign up or log in to comment # Problem Set 1 part one
# Find prime number
# Name: Ricky Sumarto
# Time: 10 minutes
#
inp = int(raw_input("Input integer 1-1000? "))
print "Your number is : " , inp
# Find odd number and put into array
Odd=[]
for x in range (2,inp+1):
if ((x%2)!=0):
Odd.append(x)
print "Load odd values array", Odd
# Find prime number
prime=[]
for x in range(0, len(Odd)):
number=Odd[x]
accum=0
for y in range(0, x):
if (number%Odd[y]==0):
accum=accum+1
if accum<=2:
prime.append(number)
print "Your prime number: ", prime
# Problem Set 1 part two:
# Calculate the log
# =========================================
totLog=0
for x in range(0, len(prime)):
totLog = totLog + log(prime[x], 10)
print 'Sum of log n:', totLog
print 'The number n is: ', inp
print 'Ratio the 2 numbers is: ', totLog/inp
Permalink
No comments. Sign up or log in to comment |
No comments. Sign up or log in to comment