Learn faster and stay on-track by joining this free class with other self-learners.
Register for MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming now.
|
MIT OpenCourseWare 6.00 Introduction to Computer Science and ProgrammingClass length: 24 weeks. Start anytime. Creator: duallain Status: Established |
Join this class! |
|
Lesson 2: Assignment 1Homework Submissions112 total# Problem 1a
def primes(max_value, final_index):
index = 1
last_prime = 0
prime_list = [2]
for num in range(3, max_value, 2):
prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
prime = False
break
if prime:
index += 1
prime_list.append(num)
if len(prime_list) > final_index:
print "The %d prime = %d" % (final_index, prime_list[final_index - 1])
return prime_list
# Problem 1b
prime_list = primes(10000, 1000)
prime_sum = 0
for i in range(len(prime_list)):
prime_sum += log(prime_list[i])
print "Log sum =", prime_sum
print "Last prime =", prime_list[len(prime_list) - 1]
print "Ratio =", prime_sum / prime_list[len(prime_list) - 1]
#Problem Set 1a
#smiller148
#Time? Longer than I anticipated, but it worked out.
# Program to find and print the 1000th prime number
prime=0
n=1
integer_candidate=2*n+1
a=1
while (integer_candidate>1):
divisor=2*a+1
if integer_candidate%divisor==0:
integer_candidate=integer_candidate+2
a=1
elif integer_candidate%divisor>0 and divisor<integer_candidate/3:
a=a+1
else:
prime=prime+1
print integer_candidate, (prime+2)
integer_candidate=integer_candidate+2
a=1
if prime==998:
print "That's the 1000th prime number, friend!"
break
# Methodology:
# Establish prime counter to start at zero
# Establish first odd integer to test
# Define divisor start
# Initiate loop for condition while integers to test are >1
# Define divisor range
# First test if the integer has the divisor as a factor
# If this is true, then find the next odd integer to test
# Reset the divisor starting condition (a=1). Failure to do this means generating false primes (like 95).
# If the divisor is not a factor, test with other divisors up to the condition where the divisor is less than 1/3 of the integer
# If there are no divisors that yield a factor, the number must be prime and the prime counter must be increased by 1
# Generate printed output to monitor program progress
# Find the next odd number to test
# Reset the divisor starting condition
# Establish program end point as when the prime counter has the value 998 (which accounts for the 3rd to 1000th prime)
#Problem Set 1b
#smiller148
# Program to sum the logs of all prime numbers, from 2 to m, and their ratios to m.
# Note: for this program to successfully execute as written, m must be a prime number equal to or greater than 5.
from math import *
m=1009
n=1
integer_candidate=2*n+1
a=1
sum_total=log(2)+log(3)
while (integer_candidate>1):
divisor=2*a+1
if integer_candidate%divisor==0:
integer_candidate=integer_candidate+2
a=1
elif integer_candidate%divisor>0 and divisor<integer_candidate/3:
a=a+1
else:
sum_total=sum_total+log(integer_candidate)
print integer_candidate, sum_total
if integer_candidate==m:
b=sum_total
c=b/m
print 'Sum of the logs of primes up to',m,'is',b,'and the sum:input integer ratio is',c,'.'
break
else:
integer_candidate=integer_candidate+2
a=1
No comments. Sign up or log in to comment # Problem Set: 1a
#Task: Print the desired prime number
#Name: Paulina Kieliba
#Time: 0:40
import numpy as np
from math import *
primes=[]
primes.append(2)
start=3
x=int(input("Which prime number do you want to compute? "))
while len(primes)<x+1:
for k in range(len(primes)):
if (start%primes[k]==0):
prime=False
break
else:
prime=True
if (prime==True):
primes.append(start)
start+=2
print "The " + str(x)+"th prime number is:",primes[x]
# Problem Set: 1b
#Task: Print the desired prime number
#Name: Paulina Kieliba
#Time: 0:05
sum=0
for n in range(len(primes)):
sum+=log(primes[n])
print "Sum of prime logs: ",sum
print "The highest prime included is: ",primes[x]
print "The ratio of those values is: ",sum/primes[x]
No comments. Sign up or log in to comment # Problem Set 1
# Name: Astragen
# Time: 2h
def éprimo(n):
if n == 2:
return 1
if n % 2 == 0:
return 0
max = n**0.5+1
i = 3
while i <= max:
if n % i == 0:
return 0
i+=2
return 1
def main():
# testar ...
x=1
while x < 1000:
x = x + 1
if éprimo (x) == 1:
print ("Número " + str(x) + " " + "é primo")
else:
print ("Número " + str(x) + " " + "não é primo")
main()
No comments. Sign up or log in to comment # Problem Set 1
# Name: aug2uag
# Collaborators: -
# Time: 1:00 #
def all_the_primes(n):
primes = []
for i in range(1,n+1):
if i%2==0 and i!=2:
print i,'is not prime!'
else:
if i%3==0 and i!=3:
print i,'is not prime!'
elif i%5==0 and i!=5:
print i,'is not prime!'
elif i%7==0 and i!=7:
print i,'is not prime!'
else:
print i,'is prime!'
primes.append(i)
print primes
#return primes from above
def print_ans (primes):
result = 0
for e in primes:
result+=math.log10(e)
return result
print result
No comments. Sign up or log in to comment #Problem Set 1a
#Name: Anubhav Nidhi
#Collaborators: None
#Time: 2 hours
#Program that computes and prints the 1000th prime number.
i=3
k=2
while i<10000 and k<=1000:
s=0
j=2
while j<i:
if i%j==0:
s=1
j=j+1
if s==0:
k=k+1
i=i+1
print i-1
#Problem Set 1b
#Name: Anubhav Nidhi
#Collaborators: None
#Time: 10 min
#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 ratio of these two quantities.
from math import *
i=3
k=2
f=int(raw_input('Enter prime num you want'))
ans=log(2.0)
while i<10000 and k<=f:
s=0
j=2
while j<i:
if i%j==0:
s=1
j=j+1
if s==0:
k=k+1
ans=ans+log(i)
i=i+1
i=i-1
print ('The '+str(f)+' prime no is '+str(i))
print('sum of log'+str(ans))
print('ratio is'+str(ans/i))
No comments. Sign up or log in to comment submission # Problem Set 1
# Name: J
# Time:
max_prime = int(raw_input('Which # prime do you want? ')) # input is only for easy testing
prime_count = 2 # skipping the nuances behind 2 and 3
test_prime = 3 # will get incremented to 5 when it enters the loop
mod_val = 2
prime_ind = 1 # will assume the number is prime until proven otherwise
while prime_count < max_prime : # beginning of main loop, only requirement is that the counter is less than the max prime being sought
test_prime += 2
mod_val = 2
# test prime and increment prime_count if prime
while (mod_val <= test_prime/2.0 and prime_ind == 1) : # the loop will exit if the prime indicator is changed to zero, or if the test value is half that of the target
if test_prime%mod_val == 0 : # if ever mod zero, exit the loop and move to next test
prime_ind = 0
else :
mod_val += 1
if prime_ind == 1 :
prime_count += 1 # increment the counter
else :
prime_ind = 1
print ('The ' + str(max_prime) + ' prime number is ' + str(test_prime))
## First wrote this module to test my ability to find prime numbers
##
##test_prime = int(raw_input('Which number would you like to test for prime-ness? '))
##
##modVal = 2
##prime_ind = 1
##
##while (modVal <= (test_prime/2.0) and prime_ind == 1) :
## if test_prime%modVal == 0 :
## prime_ind = 0
## else :
## modVal += 1
##if prime_ind == 1 :
## print str(test_prime) + ' is Prime!'
##elif prime_ind == 0 :
## print(str(test_prime) +' is Not Prime it is divisible by ' + str(modVal))
##else :
## print('something went wrong')
# Problem Set 1
# Name: J
# Time:
from math import *
max_prime = int(raw_input('Which # prime do you want? ')) # input is only for easy testing
prime_count = 2 # skipping the nuances behind 2 and 3
test_prime = 3.0 # will get incremented to 5 when it enters the loop
mod_val = 2
prime_ind = 1 # will assume the number is prime until proven otherwise
answer = log(2.0)+log(3.0)
while prime_count < max_prime : # beginning of main loop, only requirement is that the counter is less than the max prime being sought
test_prime += 2
mod_val = 2
# test prime and increment prime_count if prime
while (mod_val <= test_prime/2.0 and prime_ind == 1) : # the loop will exit if the prime indicator is changed to zero, or if the test value is half that of the target
if test_prime%mod_val == 0 : # if ever mod zero, exit the loop and move to next test
prime_ind = 0
else :
mod_val += 1
if prime_ind == 1 :
prime_count += 1 # increment the counter
answer = answer + log(test_prime)
else :
prime_ind = 1
print ('The ' + str(max_prime) + ' prime number is ' + str(test_prime))
print ('and the sum of the logs is ' + str(answer))
print ('and the ratio is ' + str(answer/test_prime))
No comments. Sign up or log in to comment ASSN 1 for MIT 6.00 OpenCourseWare #Problem Set 1a
#Name: Rajko Vujic
#Collaborators: None
#Time: A few days
#Program that computes and prints the 1000th prime number.
candidate = 3
count = 2
n = 1000
print 2, #First known prime number
while count <= n:
for x in range(2, candidate):
if candidate % x == 0:
break
else:
print candidate,
count += 1
if count <= n:
candidate += 1
print '\n' + '1000th prime number is ' + str(candidate),
#Problem Set 1b
#Name: Rajko Vujic
#Collaborators: None
#Time: A few days
#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 ratio of these two quantities.
from math import * #Use a built in mathematical functions from Python.
candidate = 3
count = 2
n = int(raw_input('Please enter a number: '))
logsum = log(2)
ratio = 0
while count <= n:
for x in range(2, candidate):
if candidate % x == 0:
break
else:
count += 1
logsum += log(candidate)
if count <= n:
candidate += 1
ratio = logsum/candidate
print '\n' + 'The sum of the logs of the prime is.....: ' +str(logsum)
print 'The number is...........................: ' + str(candidate)
print 'The ratio of these two quantities is....: ' +str(ratio)
No comments. Sign up or log in to comment In the first problem, it prints all the prime numbers for easy reference and then tells the 1000th prime number. #######Problem 1#############
cur_num=3
num_count=1
Nprime=1
print 2 #since 2 is not calculated in the algorithm
while num_count<1000: #Do while the number count is less than 1000
half_num=(cur_num/2) #divide the current number by 2(integer division)
while half_num>1: #Do while half_num variable is greater than 1
Nprime= cur_num%half_num #Do remainder division for the half_num variable
if Nprime==0: #if the remainder is 0,then its not a prime number; skip loop
break
else:
half_num=half_num-1 #else repeat with 1-half-num
if Nprime>0: #if at the end of previous loop, still there is no remainder:
num_count=num_count+1 #add 1 to number counter
print cur_num #print the number
Nprime=0
cur_num=cur_num+2 #try next odd number
final=cur_num-2
print 'The 1000th prime number is: ' + str(final) #print the final (1000) value.
##########Problem 2#############
from math import *
cur_num=3
num_count=1
Nprime=1
n=int(raw_input('Enter your number: ')) #Asks user for input number
prime_sum= log(2)
while cur_num<n: # calulates prime numbers below that number
half_num=(cur_num/2)
while half_num>1:
Nprime= cur_num%half_num
if Nprime==0:
break
else:
half_num=half_num-1
if Nprime>0:
num_count=num_count+1
prime_sum=prime_sum+ log(cur_num) #calulates the sum of the prime numbers
Nprime=0
cur_num=cur_num+2
final=cur_num-2
ratio=prime_sum/n
print 'Number entered: ' + str(n)
print 'Sum of logs of prime numbers: ' + str(prime_sum)
print 'Ratio: ' + str(ratio)
No comments. Sign up or log in to comment Problem Set 0 Name: Igor Collaborators: John Doe Time: 3:30 x = 3
y = x
count = 1
primeCount = 0
while count < 1000:
while y >= 1:
if x % y == 0:
primeCount += 1
y -= 1
if primeCount < 3:
count += 1
x += 2
y = x
primeCount = 0
print(x-2)
# Sum
from math import *
def prime():
n = int(input("Value for n : = "))
x = 2
y = x
count = 0
primeCount = 0
summan = 0
while count < n:
while y >= 1:
if x % y == 0:
primeCount += 1
y -= 1
if primeCount < 3:
count += 1
primeNumber = log(x)
summan += primeNumber
x += 1
y = x
primeCount = 0
print("Sum of prime logs is :",summan)
print("Number of prime's is :",n)
print("Ratio between them is :",(summan/n))
No comments. Sign up or log in to comment Problem 1 sum=log(2,e)
lo=0.0
import math
n2=1000
while i < n2 : ##i..th prime
n+=2##number
a=2
prime = 1
squarer=math.sqrt(n)
while prime==1 and squarer >= a :
a+=1 ##divider
if n%a==0 :
prime=0
if prime==1:
i+=1
lo=log(n,e)
sum+=lo
r=sum/n
print(i,n,lo,sum,r)
No comments. Sign up or log in to comment # Problem Set 1a
# Name: Itinarch
# Collaborators:
# Time: 1:00
#
test = 1
div = 3
counter = 0
end = 1
finalnum = 0
while counter<998:
test = test+2
div = 3
end = 0
while end == 0:
if (test%div == 0):
end = 1
else:
div = div +2
if div > (test/3):
counter = counter+1
finalnum = test
end = 1
print "The 1000th prime number is "+str(finalnum)
# Problem Set 1b
# Name: Itinarch
# Collaborators:
# Time: 0:15
#
from math import *
test = 1
div = 3
end = 1
finalnum = 0
somenum = 50000
sumofprimes = log(2)
while test<somenum:
test = test+2
div = 3
end = 0
while end == 0:
if (test%div == 0):
end = 1
else:
div = div +2
if div > (test/3):
sumofprimes = sumofprimes + log(test)
end = 1
print "The value n is "+str(somenum)
print "The sum of the logs of the primes up to n is "+str(sumofprimes)
print "The ratio of these two values is "+str(sumofprimes/somenum)
No comments. Sign up or log in to comment #Problem 1
counter = 1
test = 3
while counter < 1000:
prime = True
factor = 2
while factor < test and prime == True: #while candidate (test) is still apparently a prime and the factors we're checking haven't reached the candidate yet
if test%factor==0:
#print test, ' is divisible by ', factor
prime = False
else:
#print test, ' is not divisible by ', factor
if factor == 2:
factor = factor + 1
else:
factor = factor + 2
if prime == True:
counter = counter + 1 #counts to see when we reach 1000
if counter == 1000:
print test #, 'is a prime number, and it is number', counter
test = test + 2
#Problem 2
from math import *
for i in range(0,30,1):
test = 3
primesum = log(2)
stoppoint = int(raw_input('Enter a number for the program to test: '))
print primesum
while test < stoppoint -1:
prime = True
factor = 2
while factor < test and prime == True: #while candidate (test) is still apparently a prime and the factors we're checking haven't reached the candidate yet
if test%factor==0:
#print test, ' is divisible by ', factor
prime = False
else:
#print test, ' is not divisible by ', factor
if factor == 2:
factor = factor + 1
else:
factor = factor + 2
if prime == True:
primesum = primesum + log(test)
test = test + 2
print 'Sum of logs of primes: ', primesum
print 'The number you entered:', stoppoint
print 'Ratio:', primesum/stoppoint
print 'The highest prime included: ', test -2
No comments. Sign up or log in to comment Just a note, I didn't use for loops because I wanted to count by 2 at a time and thats just what made sense for me. Any suggestions to make it more efficient would be great. The second part doesn't rely on the first part, they are 2 separate scripts. #Problem Set 1
#Name: Nick
#Collaborators: None
#Time: 1:00
#Problem 1
number = 3 #the variable that we will be checking if it is a prime
primeCounter = 1 #Because 2 is the first prime number and our program doesn't find it
while primeCounter < 1000: #will stop loop when the 1000th prime is found
stopCheck = number/3 #last number it needs to check because 3 is the smallest possible factor of any odd number other than 1
prime = 0
i = 3
while i <= stopCheck and prime == 0:
check = number%i
if check == 0:
prime = 1
i = i+2
if prime == 0:
primeCounter = primeCounter +1
if primeCounter != 1000:
number = number +2
print number
#Problem 2
from math import *
n = raw_input('n? ') #the prime number to use to approximate e**n
approximation = log(2)#starting value because our program doesn't count 2
number = 3 #the variable that we will be checking if it is a prime
while number < n: #will stop loop when the 1000th prime is found
stopCheck = number/3 #last number it needs to check because 3 is the smallest possible factor of any odd number other than 1
prime = 0 #says that the number is a prime
i = 3 #i only needs to be odds
while i <= stopCheck and prime == 0:
check = number%i #checks what the remainder is
if check == 0:
prime = 1 #if no remainder it isnt a prime so number isnt a prime
i = i+2 #repeats the while loop with the next odd number
if prime == 0:#if it is a prime
approximation = approximation + log(number)#add it to the existing sum of primes
number = number +2 #checks the next odd number if we aren't done
ratio = approximation / n
print 'Sum of Logs:',approximation
print 'n:',n
print 'Ratio:',ratio
No comments. Sign up or log in to comment Problem Set 1 Chap 2Name: Andrew JonesCollaborators: NoneTime: 1 hour# my code generates all integers, not just odd ones... # my code does include 2 as prime # my codes works and correctly generates all primes though! # this was a great problem and really required some thought! # I wrote the problem in gedit and imported it into python #problem 1 from math import * def primer(x): e = [] prime = 2 while len(e) < x: for q in range(2, prime): if prime % q == 0 and q != prime: print str(prime) + " divided with " + str(q) prime = prime + 1 break else: e.append(prime) print str(prime) + " is prime" prime = prime + 1 print "The "+ str(len(e)) + "th prime is " + str(e[-1]) def logger(x): e = [] sumlogs = 0 prime = 2 # changed the loop so it only computes from 2 to x while prime < x: for q in range(2, prime): if prime % q == 0 and q != prime: prime = prime + 1 break else: e.append(prime) print str(prime) + " is prime" prime = prime + 1 # this will take every prime in e and sum the logs for p in e: sumlogs = log(p) + sumlogs print "The sum of the logs is " + str(sumlogs) print str(x) + " is how many primes we found" print "The ratios are " + str(sumlogs) + ":" + str(x) No comments. Sign up or log in to comment This turned out to be an adventure. I thought this would be quick but it takes a bit more time because you have to really think about the code for the first one. At least, I did. I think if I had sat down and tried it once, it could have coded it in 30 minutes, but because I thought it'd be easy and was doing it as an after thought, it took a bit longer. The second part is very easy. #Problem Set 1
#Name: Bigsonny
#Collaborators: None
#Time:A few days for problem 1 and a 10 minutes for problem 2
#
from math import *
###############Problem 1########################
#A program which computes and prints the 1000th prime numbber
#Ask user which prime # to compute
number = int(input("What prime number do you want to compute?"))
count = 1 #Keeps track of the number corresponding to the prime#
prime_candidate = 2 # candidate for prime number
prime_check = 2 # number to check if prime_candidate is prime
while count < number: #continues until the count equals the user's number
#This section is going to check if the prime_candidate is even
#If prime_candidate is even, it will make it odd by adding 1 to it
#If prime_candidate is odd, it will print the count and the prime_candidate
#It will then add 2 to teh prime_candidate to get to the next odd number
#It will also increase the count by 1
if prime_candidate % 2 == 0: #checks if it's an even number
print str(prime_candidate) + ' is even.'
prime_candidate += 1 #adds 1 to make it odd
else: #is odd
while prime_check< prime_candidate:
if prime_candidate % prime_check !=0:
prime_check +=1
else:
prime_candidate +=2
prime_check = 2
if prime_check == prime_candidate:
count +=1
prime_check =2
prime_candidate +=2
print "Count: " + str(count) + ". Prime candidate: " + str(prime_candidate-2)
#####################Problem 2####################################
#This program should compute the sum of the algorithms of the prime numbers from 2
#to some number n
#print out the sum of the logs of the primes, the number n and the ratio of these
#two quantities.
#This is just to make the output easier to read, so I'm going to label this problem 2
#and print a few lines of hash tags
print " "
print 30*"#"
print 10*"#"+"problem 2"+11*"#"
print 30*"#"
#Ask user which prime # to compute. In this case, we'll define number as n
number = int(input("What prime number do you want to compute?"))
count = 1 #Keeps track of the number corresponding to the prime#
prime_candidate = 2 # candidate for prime number
prime_check = 2 # number to check if prime_candidate is prime
sumOfLog = 0 #This variable will contain the sum of the logs
ratioOfLog = 0 #This variable will contain the ratio of the logs
while count < number: #continues until the count equals the user's number
#This section is going to check if the prime_candidate is even
#If prime_candidate is even, it will make it odd by adding 1 to it
#If prime_candidate is odd, it will print the count and the prime_candidate
#It will then add 2 to teh prime_candidate to get to the next odd number
#It will also increase the count by 1
if prime_candidate % 2 == 0: #checks if it's an even number
print str(prime_candidate) + ' is even.'
prime_candidate += 1 #adds 1 to make it odd
else: #is odd
while prime_check< prime_candidate:
if prime_candidate % prime_check !=0:
prime_check +=1
else:
prime_candidate +=2
prime_check = 2
if prime_check == prime_candidate: #found a log
#first let's ccompute the sum of the logs of the prime numbers
sumOfLog = sumOfLog + log10(prime_candidate)
#Thes now, we'll increase the values of the variables
count +=1
prime_check =2
prime_candidate +=2
#We can start by printing the prime number and corresponding count
print "Count: " + str(count) + ". Prime candidate: " + str(prime_candidate-2)
#We'll test to see if count and number are equal
print ' '
#Finally, we'll print the sum of the logs of the primes, n and then the ratio
ratioOfLog = sumOfLog/number
print "The sum of the logs of the prime is: " +str(sumOfLog)
print "The number \"n\" is: " + str(number)
print "and the ratio of the sum of the primes to the number n is: " +str(ratioOfLog)
Comments:man! I love the detail in your comments for each line. I am a total nub to programming and not all that clever at math. So reading your comments is very insightful. I have been having a hell of a time trying to figure out how, what, and where to structure everything. I have gotten as far as setting out the criteria for each piece of the code (somewhat) and what it needs to do but it is lacking. If you are OK with it and if you think it is ethical of me to do so (not cheating or is it?) I am going to copy and paste the comments and then write the code to support each comment. You have also given me great insight into how I need to proceed regarding my future assignments and early programming efforts. So that I can easily reread my work and apply my learning to future projects that I may write. On another note what is your background/experience in programming and or CompSci in general, to give me an idea of where I need to improve and how. Thanks and have a great day P.S., As far as your self grade goes I personally think you did great. Thanks machv5. I am glad that you enjoy the comments. I do them because I have always been told that it should help you AND others read your code and figure out what you intended to do and how you intended to do it. As far I am concerned, I am of the opinion that you learn by both thinking and seeing examples, so if any of the codes that I submit helps you, please use it at your leisure. I think we all learn by seeing examples which work for us and I am also interested in seeing other people's codes, so I can learn better practice, so please use it, share it, modify it. You can credit me as a collaborator or not, that doesn't bother me. The only think I would ask is that you make an effort to comment your code as well and to answer questions for others as that's how we all learn in a community like this. As far as how to think as a computer scientist, you have to just remember that computer programming is about converting a big problem in small logical steps. That is what we do. We see a problem and we ask ourselves, how to break them down into the steps to achieve them. As far as my background and experience. I took a JAVA class in undergrad, one semester. I then continued reading through the book on and off for the last few years. I followed the Java sun tutorial and joined a few forums (There is a main one for JAVA. A quick google search will point you there. You can send me a PM if you need clarification). I also studied PHP on and off and also used the w3schools website. I remember taking a true basic class in undergrad as well. Having said that, believe me, I am no programmer. I have yet to write a piece of software that is packaged with a GUI (That's my goal). I do some HTML as well. In short, if you know one language, you'll learn the others eventually. They key is being consistent. This is the first language/training program that I am aiming to finish up to truly master it. It's very easy and it's a scripting language (google it :P ). I am a noob as well. It took me a long time to do the second assignment, but if you stick to it, you'll get it. If you follow mine, I'll try to answer questions if you post comments. If i don't, send me a direct message. Thanks for the compliment and good luck. can you please change your code to outstanding? It makes me feel like my work is sub-par =) Great comments and love your work.
# Problem Set 0
# Name: Pumafied@gmail.com
# Collaborators: none
# Time: 0:20
#
x = raw_input('What is your last name?');
y = raw_input('What is your first name?');
print (y);
print (x);
raw_input()
##PS1
##Rob
#Problem 1
from math import *
def primeTest(candidate):
prime=True
if candidate%2==0: # if candidate is even,
prime=False
else:
divisor=3
while divisor <= candidate/2 and prime==True:
if candidate%divisor==0: #if candidate can be divided evenly, not prime
prime=False
else:
divisor += 2
return prime
#function to print nth prime number
def nthPrime(n):
primeCount = 1 #initial count of primes at 1 because 2 is first prime
candidate = 3
while primeCount<=n:
if primeTest(candidate)==True:
primeCount += 1
if primeCount==n:
print candidate, "is the", str(n)+"th prime number."
return
candidate +=1
else:
candidate += 1
nthPrime(100)
###Problem #2
def nthPrime(n):
primeCount = 1 #initial count of primes at 2 becuase 1 and two are first two primes
candidate = 3
sum_of_primeLog =0
while primeCount<=n:
if primeTest(candidate)==True:
primeLog =log(candidate)
sum_of_primeLogs= sum_of_primeLog + primeLog
primeCount += 1
if primeCount==n:
#print candidate, "is the", str(n)+"th prime number."
print sum_of_primeLogs, "\t", candidate, "\t", sum_of_primeLogs/candidate
return
candidate +=1
else:
candidate += 1
def testingNumberTheory():
for i in range (1,100):
nthPrime(i)
print
No comments. Sign up or log in to comment Straight forward assignment. The logarithm portion took me awhile to code. My math skills are rusty. #!/usr/local/bin/python ## Problem 1. Write a program that computes and prints the 1000th prime number. ## This problem took just over one hour to program. # start with the first candiate candidates = [1,3] # start with the know primes primes = [2] def next_odd_number(x): """ This function takes an odd number and returns the next odd number. """ if x%2 == 0: print "Error: next_odd_number was pass an non-odd number." return None else: return x+2 def isPrime(x): """ This function takes an integer and returns a 1 if the number is prime and a 0 if it is not prime. """ counter = 1 while counter <= x/2: #print counter #print x/2 counter = counter + 1 #print counter if x%counter == 0: return 0 return 1 print 'Begining of Problem 1.' while len(primes) <= 1000: if isPrime(candidates[-1]): primes.append(candidates[-1]) # print primes # else: # print candidates[-1], 'is not prime' next_candidate = next_odd_number(candidates[-1]) candidates.append(next_candidate) print primes[999] print 'end of Problem 1.' print print ## Problem 2. 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. ## You should be able to make only some small changes to your solution to Problem 1 to solve this problem as well. ## Hints: While you should see the ratio of the sum of the logs of the primes to the value n slowly get closer to 1, it does not approach this limit monotonically. ## Probably took two hours+ to make this work. print 'Begining of Problem 2.' import math from math import * def find_primes_up_to_n(n): """ This function takes a number, n, and returns the largest prime less than or equal to n. """ # start with the first candiate candidates = [1,3] # 1,3,5,7,11,13,17,19 # start with the lowest known prime primes = [2] prime_sum = 0.0 while primes[-1] <= n: if isPrime(candidates[-1]): primes.append(candidates[-1]) prime_sum = prime_sum + math.log(primes[-1]) next_candidate = next_odd_number(candidates[-1]) candidates.append(next_candidate) primes = primes[0:-1] print 'N', n,'; the largest prime <=', n, 'is', primes[-1], ';Sum of logs:', prime_sum return prime_sum trials = [5,7,956,78,98,1454,3412,6789,23124] for each in trials: answer = find_primes_up_to_n(each) print 'and the ratio of these two quantities is ', each / answer print 'end of Problem 2.' No comments. Sign up or log in to comment Ps1a Ps1b # Problem set 1a
# Name: Shemmerson
# Collaborators: CuriousReef
# Time: 2 Hrs
#finds 1000th prime
y = 1000
x=2
count=1
print "Finding 1000th prime"
while count<=y:
prime=True
for test in range (2, x):
if x%test == 0:
prime=False
if prime==True:
count = count + 1
print x,
if count<=y:
x = x + 1
print
print `x` + " is the " + `y` + "th prime"
#Problem set 1b
# Name:Shemmerson
# Collaborators: CuriousReef
# Time: .30 Hrs
#finds and prints all primes to 1000 + sum of logs
import math
x = 2
count = 1
log = 0
y = 1000
print "Finding 1000th prime."
while count<=y:
prime=True
for test in range(2,x):
if x%test ==0:
prime=False
if prime==True:
count += 1
log = log + math.log(x)
print x
if count <=y:
x = x + 1
print `x` + " is the " + `y` + "th prime"
print `count-1` + " is the total log count"
print `log` + " is the sum of the logs"
No comments. Sign up or log in to comment #Problem Set 1
#Name: Andrew
#Collaborators: CuriousReef
#Time:
from math import *
#problem 1
def isPrime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3,int(ceil(sqrt(num)))+1,2):
if num % i == 0:
return False
return True
def primeFinder(num):
primesFound = 0
test = 0 #number we're testing
while primesFound < num:
test += 1
if isPrime(test):
primesFound += 1
return test
#problem 2
def sumLogPrime(num):
primesFound = 0
test = 0
total = 0
while primesFound < num:
test += 1
if isPrime(test):
total += log(test)
primesFound += 1
print "The sum of the log of the primes:",total
print "The number n:",num
print "The ratio of these two quantities:",float(total)/float(num)
return total
###prints sum of log of primes. n. and the ratio of those two.
if __name__ == "__main__":
sumLogPrime(1000)
No comments. Sign up or log in to comment PS 1.1 / 1.2 #PS 1
#Jill Ann
#Problem set 1.1
def countPrime(n):
x=2
count=1
while count<=n:
prime=True
for test in range (2,x):
if x%test == 0:
prime=False
if prime==True:
count+=1
if count<=n:
x+=1
print `x` + " is the nth prime"
#Problem set 1.2
import math
x=2
count=1
logtable=0
while count<=1000:
prime=True
for test in range(2,x):
if x%test ==0:
prime=False
if prime==True:
count+=1
logtable+=math.log(x)
if count <=1000:
x+=1
print `x` + " is our final prime, ladies and gentlemen"
print `count-1` + " is the total count"
print `logtable` + " is the sum of the natural logs, per assignment"
No comments. Sign up or log in to comment Got stuck on the first one for awhile. Turned out that I had forgotten to reset my testdiv to 2 when it found a number that wasn't prime. So it would go through the first 30 primes just fine but then when it got to 31 it would start returning non-prime numbers because testdiv was starting out higher than the number that would divide testnum evenly. Problem 2 took about 25 minutes. Just needed to change it from a count down to a test to make sure your testnum was less than the number in question, n in this case. The other change was to make sure that when the system found a prime number that it added that number to a variable that I called sumlogs. This variable starts with a value of log(2) to account for 2 being left out of the test. Don't forget to make sure your variables are properly configured as integers or floats. #Problem Set 1
#Dino3317OSU
##Problem 1
prime = raw_input('Which prime # would you like to know? ')
testnum=3
testdiv=2
count=int(prime)-1
while count>0:
if testnum==testdiv:
count=count-1
testnum=testnum+2
testdiv=2
else:
if testnum%testdiv==0:
testnum=testnum+2
testdiv=2
else:
testdiv=testdiv+1
else:
print testnum-2, 'is #', prime
##Problem 2.
from math import *
n = raw_input('What is n? ')
testnum=3
testdiv=2
sumlogs=log(2)
while testnum<int(n):
if testnum==testdiv:
sumlogs=sumlogs+log(testnum)
testnum=testnum+2
testdiv=2
else:
if testnum%testdiv==0:
testnum=testnum+2
testdiv=2
else:
testdiv=testdiv+1
else:
print 'The sum of all the prime logs under ',n,' is ',sumlogs
print 'The ratio is', float(sumlogs)/float(n)
Comments:For problem set1a, the prime numbers, why do you subtract 1 from the count? problem 1- done problem 2- done too :D ##### Assignment 1 #####
#####################################
##### Problem Set 1 #####
##### Name: Wolfei #####
##### Collaborators: Internet #####
##### Time: 1 week #####
def PrimeSolver3():
a = 1
b = 1
c = a-1
d = 1
counter = 2
i = 1
divisors = 0
while counter <= 1000:#number of prime to stop
if ((a/2)*2) != a:#odd numbers go through
if divisorFinder(a) == 1:#numbers with 1 divisor go through
print a, counter
a += 1
counter += 1
else:a+=1
else: a += 1
print 'THE 1000TH PRIME NUMBER IS', (a-1)
def divisorFinder(x):
""" Finds the Divisors of any number"""
a = 1
numberofdivisors = 0
while(a<x):
if x%a == 0:#numbers that divide perfectly pass
a = a + 1
numberofdivisors += 1
else: a = a + 1#otherwise sent back to loop with an added 1
return numberofdivisors
#####################################
##### Problem Set 2 #####
##### Name: Wolfei #####
##### Collaborators: Internet #####
##### Time: 2days #####
from math import*
def SumsandRatio(n):
""" SumLog(primes) and ratio between <<< and n"""
a = 1
b = 1
c = a-1
d = 1
counter = 0
i = 1
divisors = 0
sumlogs = log(2)
while counter <= n:#number of prime to stop
if ((a/2)*2) != a:#odd numbers go through
if divisorFinder(a) == 1:#numbers with 1 divisor go through
logs = log(a)
sumlogs += logs
a += 1
counter += 1
else:a+=1
else: a += 1
counter += 1
print 'The sum of logs = ', sumlogs
print 'Number n = ', n
print 'Ratio between sumoflogs and n is :', sumlogs/n
Comments:I tried your code and it works, however most other Prime number testers have a line somewhere that goes something like this while (n <= (number**.5)): It is the half value being used in the test I am talking about. Why does yours not need one and or how does it compensate for not having it? Does yours take longer to compute each number it tests because of not having it? i'm glad to hear it works :D, about the (n _<, but thanx for your comment i will come back to this assignment to see if i can answer any of your questions after testing and looking at other prime number testers Completed a week or two ago, didn't realize there was an online submission at the time. CC welcome on all submissions. #Problem Set 1, Problem 1
#Name: Charlie Roselius
#Collaborators: None
#Time: Approximately 0:30 (completed earlier)
#
primes_found = 1 #Start testing numbers at 3, so 2 has been found.
potential_prime = 1 #Initialized, but will be 3 in first loop.
while primes_found < 1000: #The 1000th prime will be the last iteration of this loop.
potential_prime += 2 #Only check odd numbers.
is_prime = 1 #Litmus variable for result of prime test.
for i in range(2,potential_prime): #Iterate over potential divisors.
if potential_prime % i == 0: #If remainder is zero, we found a divisor and...
is_prime = 0 #the number is not prime...
break #so we can stop testing for more divisors.
if is_prime == 1: #If we weren't able to find any divisors, this number is prime.
primes_found += 1 #Increment our prime counter, loop back to beginning of while block and check for whether this was the 1000th prime.
print potential_prime #As the last iteration of the while loop will have been the 1000th prime, we can simply print this.
#Problem Set 1, Problem 2
#Name: Charlie Roselius
#Collaborators: None
#Time: Approximately 0:30 (completed earlier)
#
from math import * #Needed to compute logs.
print "Please enter n"
n = int(raw_input()) #CCREQUEST: Is n a good variable name?
sum_of_logs = 0
potential_prime = 1 #We need to identify the primes to use in our sum of logs. Please refer to above for algorithm comments.
while potential_prime<n+1:
is_prime = 1
for i in range(2,potential_prime):
if potential_prime % i == 0:
is_prime = 0
break
if is_prime == 1:
sum_of_logs += log(potential_prime) #Sum the primes as we come across them.
potential_prime += 2
#Now we can print our results.
print "The sum of the logs of the primes is: " + str(sum_of_logs) + "\n"
print "N was: " + str(n) + "\n"
print "Their ratio is: " + str(sum_of_logs/n)
No comments. Sign up or log in to comment take a look at my code and some critique is greatly appreciated! i'm sure it could be cleaner and more "mathmatically correct" but it computes and not bugged as far as i'm concerned. just the first problem is coded not the second one pc=2
var=3
while (pc<1000):
div=2
var=var+2
while var%div!=0:
div=div+1
if var%div==0 and var==div:
pc=pc+1
print var
No comments. Sign up or log in to comment Problem 1 took me a LONG time because I was constantly stuck in infinite loop. After hours and days of thinking, my solution was to print every single numbers (when i run the program) so that I could see where the infinite loop was at. After finding that solution, it took me only a couple more hours to figure out. Problem 2 took me about 3 hours. This part should've been easy, but I wasn't getting the right answer because I misunderstood the procedure. Just for other's sake I will tell you that the ratio between sum of logs of primes and log of 'n'th number NOTE After going over others' assignment (to understand part2) I noticed that not everyone had the right answer. I advice others to check if these answers are right before actually using others' work as references # Problem Set 1 Problem 1
# Name: Boo Park
# Collaborators: none
# Time: 8hours+ couldn't figure out why i was stuck on infinite loop for the longest time.
#
# Write a program that computes and prints the 1000th prime number.
count = 1 # which prime number the candidate is
candidate = 2 # candidate for prime number
test_num = 2 # number that will be used to test candidate to check for prime number
while count < 1000: # the program will run only until the 1000th prime number
if candidate % 2 == 0: # check if the candidate is even
candidate += 1 # make the candidate as an odd number
print 'candidate: ' + str(candidate)
else: # if the candidate number is odd
while test_num < candidate: # run only while the test number is smaller than the candidate number
if candidate % test_num != 0: # check if the candidate number is divisible by the test_num
test_num += 1 # change test_num if candidate is not a prime number.
else: # the candidate number IS divisible by test_num and candidate number is not a prime number
candidate += 2 # since non-prime number is divisible by test_num, change it
test_num = 2 # return test_num to 2
if test_num == candidate: # we found a prime number
count += 1 # tell the counter that we found another prime number
print 'prime number ' + str(count) + ' is ' + str(candidate)
test_num = 2 # return the test_num to 2 in order to find the next prime number
candidate += 2 # change the candidate number in order to find the next prime number
candidate -= 2
print '1000TH PRIME NUMBER IS: ' + str(candidate) # will print the candidate number as prime number when the program is not running anymore
# Problem Set 1 Problem 2
# Name: Boo Park
# Collaborators: none
# Time: 3hours+ didn't understand what the procedure actually meant. found out that the ratio actually meant 'sum of log(primes)' vs 'log('n'th prime).
# NOTE: After I went through others' assignment 1 problem 2, I found out that not everyone had the right answers. If you are using their examples, then make sure that they are right before following their assignments.
# 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.
import math
from math import *
count = 1 # which prime number the candidate is
candidate = 2 # candidate for prime number
test_num = 2 # number that will be used to test candidate to check for prime number
log_p = math.log(2) # sum of logs of prime numbers
log_n = 0 # log of n
ratio = 0 # ratio of log_p and log_n
n = raw_input('Enter an integer for n') # ask for n
n = float(n) # make n a float so log can be used
while count < n: # end at the 'n'th number
if candidate % 2 == 0: # check if the candidate is even
candidate += 1 # make the candidate as an odd number
else: # if the candidate number is odd
while test_num < candidate: # run only while the test number is smaller than the candidate number
if candidate % test_num != 0: # check if the candidate number is divisible by the test_num
test_num += 1 # change test_num if candidate is not a prime number.
else: # the candidate number IS divisible by test_num and candidate number is not a prime number
candidate += 2 # since non-prime number is divisible by test_num, change it
test_num = 2 # return test_num to 2
if test_num == candidate: # we found a prime number
count += 1 # tell the counter that we found another prime number
candidate = float(candidate) # change candidate to a float so that log() can be used
log_p += math.log(candidate) # log of candidate added to log_p each time a prime number is found
test_num = 2 # return the test_num to 2 in order to find the next prime number
candidate += 2 # change the candidate number in order to find the next prime number
nth_p = candidate-2 # find the 'n'th prime number
print 'n: ' + str(n)
print 'Sum of logs of prime numbers from 2 to n is: ' + str(log_p) # sum of the logs of prime numbers
print 'Ratio of log_p to log_n is: ' + str(log_p/(nth_p)) # ratio between the sum of logs of prime numbers to the log of 'n'th number
No comments. Sign up or log in to comment # Problem Set 1a
# Name: MORAYI
# Collaborators: Curious Reef: duallain
# Time: 2+ days
#
from math import log
primeCandidate = 3
primeCounter = 1
primes = [2]
logSum=0
primeLimit = int(raw_input('Please enter upper limit of primes: '))
def isprime(n):
for x in primes:
if n % x == 0:
return False
return True
while ( primeCounter < primeLimit ):
if isprime(primeCandidate) == True:
primes.append(primeCandidate)
primeCounter += 1
primeCandidate += 2
else:
primeCandidate += 1
#####
# Problem Set 1b
# Name: MORAYI
# Collaborators: Curious Reef: duallain
# Time: 0:30 min
n = primes[-1]
for x in primes:
if x <= n:
logSum = logSum + log(x)
print primes
print "the sum of log(prime) where prime <= n = ", logSum
print "n = ", n
print "The ratio of logSum/n = ", logSum/n
No comments. Sign up or log in to comment Any questions or comments is appreciated. #Problem Set 1A
#Display Prime Numbers 1 to 1000
from math import sqrt # import the square root function
count = 1 # variable for counting 1 to 1000
display_prime = 0 # variable to finally value to be displayed
oddnum = 0 # variable for odd number to be checked from possible prime
count_primecheck = 0 # variable for counting which numbers to check against odd number
finalcheck = 0 # variable for remainder of the final check for prime
while (count <= 1000): # Loop for checking number from 1 to 1000
count += 1
if count == 2: # Check to see if number is equal to 2 if so display it
display_prime = count
print display_prime
if count%2 != 0: # Check to see if number is odd
oddnum = count
count_primecheck =1
while (count_primecheck < sqrt(oddnum)): # If number is odd preform following checks until
# the square root of that number is reached
count_primecheck +=1
finalcheck = oddnum%count_primecheck
if finalcheck == 0: # If the remainder is equal to zero check next number
count_primecheck +=1
break
if finalcheck !=0 and count_primecheck > sqrt(oddnum): # If the remainder is not equal to zero and the
# the square root has been reached dispaly number
display_prime = oddnum
print display_prime
#Problem Set 1B
#Get range of prime numbers from user and display "sum of the logarithms" and the "ratio of the sum"
from math import * # import the square root and log function
count = 1 # variable for counting 1 to the range given
display_prime = 0 # variable to finally value to be displayed
oddnum = 0 # variable for odd number to be checked from possible prime
count_primecheck = 0 # variable for counting which numbers to check against odd number
finalcheck = 0 # variable for remainder of the final check for prime
total = 0 # variable for sum of logarithms
ratio = 0.0 # variable for the ratio of the sum of logarithms
range_input = raw_input ("Enter Number ") # Get user number input
while (count < int(range_input)): # Loop for checking number from 1 to the length given
count += 1
if count == 2: # Check to see if number is equal to 2 if so add the sum of the logarithm
display_prime = count
total += log(2)
if count%2 != 0: # Check to see if number is odd
oddnum = count
count_primecheck =1
while (count_primecheck < sqrt(oddnum)): # If number is odd preform following checks until
# the square root of that number is reached
count_primecheck +=1
finalcheck = oddnum%count_primecheck
if finalcheck == 0: # If the remainder is equal to zero check next number
count_primecheck +=1
break
if finalcheck !=0 and count_primecheck > sqrt(oddnum): # If the remainder is not equal to zero and the
# the square root has been reached add the sum of the logarithm
display_prime = oddnum
total += log(display_prime)
print "The sum of the logarithms of all primes from 2 to",range_input,":", total
ratio = total/int(range_input)
print "The ratio of the sum logarithms:", ratio
No comments. Sign up or log in to comment It makes sense to me and it works. I'm sure it could be much better but I'm just learning. All input is appreciated. # Problem 1A
number=2
prime=1
# Loop through for all numbers
while (prime < 1000):
# check if number is even
if (number % 2 == 1):
# test for prime numbers
n = 2
while (n <= (number**.5)):
# if not prime break loop
if (number % n == 0):
break
# otherwise contine through possibilities
else:
n = n + 1
# none prime increments counter
if (number % n == 0):
number = number + 1
# primes increments prime counter
else:
prime = prime + 1
# print prime, ' : ', number # test
# none prime increments counter
number = number + 1
# Print 1,000th Prime
print number - 1
# Problem 1B
import math
number=2
prime=1
primes=(2,)
# Loop through for all numbers
while (prime < 1000):
# check if number is even
if (number % 2 == 1):
# test for prime numbers
n = 2
while (n <= (number**.5)):
# if not prime break loop
if (number % n == 0):
break
# otherwise contine through possibilities
else:
n = n + 1
# none prime increments counter
if (number % n == 0):
number = number + 1
# primes increments prime counter
else:
# adds primes to a tuple
primes = primes + (number,)
prime = prime + 1
# print number # test
# none prime increments counter
number = number + 1
# Print 1,000th Prime from the last index of a tuple
print (str(primes [-1]) + " is the 1,000th Prime Number")
#Compute the sum of all the logs of primes from 2 to N (some number).
print ("(The Sum, The Prime, The Ratio)")
total = 0
for N in primes[:]:
total = math.log(N) + total
if (N == primes[99]):
print (total, primes[99], float(total/primes[99]))
if (N == primes[250]):
print (total, primes[250], float(total/primes[250]))
if (N == primes[500]):
print (total, primes[500], float(total/primes[500]))
if (N == primes[750]):
print (total, primes[750], float(total/primes[750]))
# Print the sum, the number N, and the ratio of the two
print (total, primes[-1], float(total/primes[-1]))
Comments:Like how your code is written. Easy to follow and comments make it very clear what steps you were taking to test. import math import itertools def isPrime(num): limit = int(math.sqrt(num)) for i in xrange(2, limit+1): if num%i == 0: return False return True def primes(): yield 2 num = 3 while True: if isPrime(num): yield num num += 2 print 1000th numberthousandth = next(itertools.islice(primes(), 999, 1000)) print thousandth def primes_with_sum_of_logs(): yield 2, 0 num = 3 sum_of_logs = 0 while True: if isPrime(num): yield num, sum_of_logs sum_of_logs += math.log(num) num += 2 for num, sum_of_logs in itertools.islice(primes_with_sum_of_logs(), 1000): print num, sum_of_logs, sum_of_logs / num No comments. Sign up or log in to comment # Problem Set 1, part A
# Name: cmlilley
# Collaborators: none
# Time: lots
candidate = int(99)
successes = int(25)
import math
while successes < 1000 : #for all candidates before successes = 1000
tester = int(math.sqrt(candidate)) + 1 #setup your tester via the sqrt
while tester > 1 : #then, until tester = 1
if candidate%tester == 0 : #if tester divides cleanly,
candidate = candidate + 2 #set next candidate and
tester = 1 #bail out of this while loop
elif candidate%tester != 0 : #or if it doesn't divide cleanly
if tester != 2 : #and the tester is not yet 2
tester = tester - 1 #then setup the next tester
else : #but if it doesn't divide and the tester is already 2
candidate = candidate + 2 #then set the next candidate
successes = successes + 1 #and declare a success
tester = 1 #and bail out of this while loop
print (str(candidate-2) + ' is prime number ' + str(successes)) #declare the results
# Problem Set 1, part B
# Name: cmlilley
# Collaborators: none
# Time: lots
candidate = int(3)
import math
sum = math.log(2)
n = int(raw_input ('Please enter the number we will use in our computation of the sum of the logs of the primes: '))
while candidate < n : #for all candidates before candidate = n
tester = int(math.sqrt(candidate)) + 1 #setup your tester via the sqrt
while tester > 1 : #then, until tester = 1
if candidate%tester == 0 : #if tester divides cleanly,
candidate = candidate + 2 #set next candidate and
tester = 1 #bail out of this while loop
elif candidate%tester != 0 : #or if it doesn't divide cleanly
if tester != 2 : #and the tester is not yet 2
tester = tester - 1 #then setup the next tester
else : #but if it doesn't divide and the tester is already 2
sum = sum + math.log(candidate) #calculate the log of the candidate and add to sum
candidate = candidate + 2 #then set the next candidate
tester = 1 #and bail out of this while loop
ratio = sum/n
print ('The sum of the logs of primes below ' + str(n) + ' is ' + str(sum) + '.')
print ('The ratio of n to that sum is ' + str(ratio))
No comments. Sign up or log in to comment # Problem Set 1
# Name: Hans Jacob T. Stephensen (Dith)
# Collaborators: None
# Time: 0:43 (Different attempts.. it's an ineffectient program. but it works)
primecount = 1 #variable to keep track of primes
number = 3 #variable to cycle through
while 1: #Unending loop - stopped by "break" later in the program
for i in range(2,number):
if number%i == 0: #Checks all possible devisors and break if one is found
#print number, 'is not prime'
break
else: #If break is not used this else is run ("stole" this trick from the python documentation)
primecount += 1
#print number, 'is prime', 'count:', primecount
if primecount == 1000:
print 'prime 1000: ', number
break
number += 1
No comments. Sign up or log in to comment PS1 - any suggestions/comments would be appreciated. # Problem Set 1a
# Name: mattb
# Collaborators: Curious Reef
# 2 days
count = 1
candidate = 3
while count < 1000:
divisor = candidate/2
while divisor > 1:
if candidate % divisor == 0:
candidate += 2
divisor = candidate / 2
else:
divisor -= 1
count += 1
if count < 1000:
print count, ' : ', candidate
candidate += 2
print 'The 1000th prime is:', candidate
# Problem Set 1b
# Name: mattb
# Collaborators: Curious Reef
# Time: 6 hours
import math
candidate = 3
n = int(raw_input('n = '))
logsum = math.log(2)
while candidate < n - 1:
divisor = candidate/2
while divisor > 1:
if candidate % divisor == 0:
candidate += 2
divisor = candidate / 2
else: divisor -= 1
lastprime = candidate
logsum += math.log(candidate)
candidate += 2
print 'n = ', n
print 'Sum of logs = ', logsum
print 'Ratio = ', (logsum/(n))
No comments. Sign up or log in to comment ######
##1a##
#####
# -*- coding: cp1252 -*-
primos = [2];
numeroAnalizado = 0;
while len(primos) < 1000: ## Mientras la lista contenga menos de 1000 números primos
## print 'Primo num: ' + str(len(primos));
if primos[(len(primos) - 1)] == 2: ## Comprueba si es la primera iteración
numeroAnalizado = 3;
## print 'El numero analizado es 2';
else: ## Si no lo es, recorre los impares
numeroAnalizado = numeroAnalizado + 2;
## print 'El numero analizado es ' + str(numeroAnalizado);
for divisor in primos: ## Utiliza los propios números primos como divisores (descomposición factorial)
if (numeroAnalizado % divisor) == 0:
## print str(numeroAnalizado) + ' no es primo';
break
else: ## A menos que encuentre un valor entre los primos para el que el resto sea 0, añade el número a la lista
## print str(numeroAnalizado) + ' es primo';
primos.append(numeroAnalizado);
## print 'Primos contiene ahora:';
## print primos;
print str(primos[len(primos)-1]) ## Imprime el último elemento de la lista
######
##1b##
#####
# -*- coding: cp1252 -*-
from math import *;
primos = [2];
numeroAnalizado = 0;
limite = 412387;
sumaLogs = 0;
ratio = 0;
logPrimos = [];
for numeroAnalizado in range(limite):
## print 'Primo num: ' + str(len(primos));
if primos[(len(primos) - 1)] == 2:
numeroAnalizado = 3;
## print 'El numero analizado es 2';
else:
numeroAnalizado = numeroAnalizado + 2;
## print 'El numero analizado es ' + str(numeroAnalizado);
for divisor in primos:
if (numeroAnalizado % divisor) == 0:
## print str(numeroAnalizado) + ' no es primo';
break
else:
## print str(numeroAnalizado) + ' es primo';
primos.append(numeroAnalizado);
## print 'Primos contiene ahora:';
## print primos;
print 'El ultimo primo es: ' + str(primos[len(primos)-1]);
print 'El limite n es: ' + str(limite);
for numero in primos:
logPrimos.append(log(numero));
for logaritmo in logPrimos:
sumaLogs = sumaLogs + logaritmo;
print 'La suma de los logaritmos de los primos hasta ' + str(limite) + ' es de: ' + str(sumaLogs);
ratio = sumaLogs/limite;
print 'El ratio es de: ' + str(ratio);
No comments. Sign up or log in to comment Problem Set 1# Problem 1
def is_prime(n):
divisors = []
for i in range(1, n/2+1):
if n%i == 0:
divisors.append(i)
if divisors == [1]:
return True
else:
return False
def nth_prime(num):
current = 3
primesFound = 1
assert num != 1
while primesFound < num:
if is_prime(current):
if primesFound == num-1:
break
current += 2
primesFound += 1
else:
current += 2
return current
# Problem 2
from math import *
def prime_log_sums(num):
lSum = 0
for i in range(1, num,2):
if is_prime(i):
lSum = lSum + log(i)
lSum = lSum + log(2)
return lSum, num, lSum/num
No comments. Sign up or log in to comment # Problem set #1
# Problem #1
# Gio
import math
def is_prime(n):
n = float(n)
if n%2 == 0 and n != 2:
return False
for x in range(2, int(math.sqrt(n)) +1):
if n%x == 0:
return False
return True
def nth_prime(n):
i = 0
num = 1
while i < n:
num += 1
if is_prime(num):
i += 1
print num
nth_prime(1000)
############################
# Problem Set #1
# Problem 2
# Gio
import math
def is_prime(n):
n = float(n)
if n%2 == 0 and n != 2:
return False
for i in range(2, int(math.sqrt(n) +1)):
if n%i == 0:
return False
return True
def log_prime(n):
i = 0
num = 1
sum_log_prime = 0
while i < n:
num += 1
if is_prime(num):
sum_log_prime = sum_log_prime + math.log(num)
i += 1
print 'Sum:',sum_log_prime,'Prime number:',num,'Ratio:',num/sum_log_prime
log_prime(100)
No comments. Sign up or log in to comment Second program for MIT course.#Problem Set 1
#Name: Nick
#Collaborators: None
#Time: 1 day
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
while (value <= stop_value):
if (next_prime%value == 0):
is_prime = False
value = stop_value+1
else: value = value + 1
if (is_prime):
count = count + 1
#print count, ': ', next_prime
print 'The 1000th prime is ' + str(next_prime)
#2
from math import *
first_prime = 2
max_prime_count = raw_input('How many prime numbers: ')
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
while (value <= stop_value):
if (next_prime%value == 0):
is_prime = False
value = stop_value+1
else: value = value + 1
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
No comments. Sign up or log in to comment Part 1
import math
nums = range(2,10000)
for i in range(2,10000):
nums = filter(lambda x: x == i or x % i, nums)
nums2=nums[0:1000]
print nums2[999]
Part 2
import math
nums = range(2,10000)
for i in range(2,10000):
nums = filter(lambda x: x == i or x % i, nums)
nums2=nums[0:1000]
print nums2[999]
n=input('Please enter a number n ')
num_logs=range(1,n+1)
num_logs2=0
i=0
while i<n:
num_logs[i]=math.log(nums2[i])
i = i + 1
print num_logs
num_sum=sum(num_logs)
print num_sum
ratio = float(num_sum)/float(nums2[n])
print nums2[n]
print ratio
No comments. Sign up or log in to comment program1limit = 10000
prime_list = [2]
for n in range (3, limit):
for m in range(2, n):
if n%m == 0:
break
else:
prime_list.append(n)
print ("length of list = ",prime_list)
print ("length of list = ", len(prime_list))
print ("thousand'th prime = ", prime_list[999])
print ("last prime = ", prime_list[-1])
##program 2
import math
a = 3
b = 1
c = int (input("Please Enter a Number"))
d = math.log(2)
while a < c:
v = 3
while (v < math.sqrt(a) and a%v <= 0):
v += 2
if v > math.sqrt(a):
d += math.log(a)
a += a + 2
print (d)
print (a)
w = d/ a
print (w)
No comments. Sign up or log in to comment ## Problem Set 1
## Problem 1 =====================================
## Initializing Variables
potentialP = 3 # Potential Prime number being tested
countofP = 1 # Number of Primes generated (starts
# at 1 because 2 is assumed to be known)
testdivisor = 3 # The integer by which the potential prime is
# divided by
## Prime Generating Program
while countofP < 1000: # Searches for primes so long as the required number
# of primes hasn't been reached
while potentialP%testdivisor != 0: #Finds the first divisor for the current potentialP
testdivisor += 2
if potentialP == testdivisor: # If the first generated divsor is equal to
# potentialP, then it is a prime. In that case, print
# potentialP and increase the count of primes by 1
print potentialP
countofP += 1
testdivisor = 3 # Reset testdivisor
potentialP += 2 # Generate next potential prime number
from math import *
## Problem 2 =====================================
## Initializing Variables
potentialP = 3 # Potential Prime number being tested
countofP = 1 # Number of Primes generated (starts
maxnumofP = 2000 # Desired Number of Primes to be generated
testdivisor = 3 # The integer by which the potential prime is
# divided by
SumOfLogs = log(2) # Sum of the natural log of primes generated.
# Starts at log(2) because 2 is not generated
## Program summing the natural logarithms of all primes
## up to maxnumofP
while countofP < maxnumofP: # Searches for primes so long as the requested number
# of primes hasn't been reached
while potentialP%testdivisor != 0: #Finds the first divisor for the current potentialP
testdivisor += 2
if potentialP == testdivisor: # If the first found divsor found is equal to
# potentialP, then it is a prime. In that case,
# add the log of the prime to SumOfLogs and
# increase the count of primes by 1
SumOfLogs += log(potentialP)
countofP += 1
testdivisor = 3 # Resets testdivisor
potentialP += 2 # Generates next potential prime number
print SumOfLogs
print maxnumofP
print SumOfLogs/maxnumofP
No comments. Sign up or log in to comment #Problem Set 1 - Problem 1
#Name: Username53
#Collaborators: None
#Time: 2 days
print "This program will find and display the 1000th prime"
n = 1000 #Sets limit on program
counter = 1 #Starts prime number counter at one (2 already counted)
prime = 3 #First test number is 3
limit = n #Total is limit
while (counter < limit): #Run only while the # of primes is less than limit
divisor = prime/2 #Divisor is the prime num./2 (integer division gives original divisor value of 1)
while (divisor > 1):
if prime % divisor == 0: #Tests if a number is prime
prime += 2 #If number is not prime, next odd number is selected
divisor = prime / 2 #Divisor is now set to next odd number/2
else: divisor -= 1 #Number is prime
counter += 1 #Increasers counter by 1
prime += 2 #Selects next odd number
print prime - 2 #Once 1000th prime is reached, it is printed
#Problem Set 1 - Problem 2
#Name: Username53
#Collaborators: None
#Time: 1 hour
print "This program will findthe 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."
import math #gets math tools
prime = 3
counter = 1 #counter
limit = int (raw_input("Please Enter a Number")) #Input total number of primes desired
sum_of_primes = math.log(2) #Start with log of 2
while prime < limit: #Run only while prime<limit
divisor = 3 #Start with divisor of 3
while (divisor < math.sqrt(prime) and prime%divisor <> 0): #This is done when divisor < sqrt (prime) and for primes
divisor += 2 #Sets divisor to next
if divisor > math.sqrt(prime):
sum_of_primes = sum_of_primes + math.log(prime) #Add log of prime to sum of the log of primes
prime += 2 #Sets prime to next odd integer
print sum_of_primes #Prints sum of the log of primes
print prime #The prime number chosen
ratio = sum_of_primes / prime #gets ration of sum to number chosen
print ratio #prints ratio
No comments. Sign up or log in to comment Creates a tuple up to the Nth prime number. It checks the remainder from dividing the candidate for prime against all the other numbers in the tuple, stopping when the divisor**2 is greater than the candidate and moving on to the next number. # Problem Set 1
# tuckertuck
# Time = 4 days
prime_candidate = 1
count = 1
primes = (2,)
total = raw_input('nth prime number: ')
if str.isdigit(total):
total = int(total)
while count < total:
prime_candidate += 2 # generates odd numbers
for i in primes[0:]:
if prime_candidate%i == 0 and prime_candidate == i:
continue
elif prime_candidate%i == 0 and prime_candidate != i:
break
elif i*i < prime_candidate and prime_candidate%i != 0: #stops checking when i**2 is greater than prime_candidate for efficiency
continue
else: #prime_candiate is prime if it doesn't meet the other conditions of the seive and added to tuple
primes += (prime_candidate,)
count += 1
break
print 'the', total,'nth prime number is', primes[total-1]
else:
print 'please use a positive integer'
# Problem Set 2
# tuckertuck
# Time = 1 hour
from math import *
prime_candidate = 1
count = 1
primes = (2,)
total = raw_input('nth prime number: ')
if str.isdigit(total):
total = int(total)
while count < total:
prime_candidate += 2 #generates odd numbers
for i in primes[0:]:
if prime_candidate%i == 0 and prime_candidate == i:
continue
elif prime_candidate%i == 0 and prime_candidate != i:
break
elif i*i < prime_candidate and prime_candidate%i != 0:
continue
else: #prime_candiate is prime and added to list
primes += (prime_candidate,)
count += 1
break
print 'the', total,'nth prime number is', primes[total-1]
n = primes[total-1]
log_sum = 0
for i in primes[0:total]:
log_sum += log(i)
ratio = log_sum/n
print 'The sum of the logs up to',total,'is:', log_sum
print 'The ratio of the sum to n is:', ratio
else:
print 'please use a positive integer'
No comments. Sign up or log in to comment #-------------------------#
# Lecture 2, Assignment 1, Problem 1
#
# Author: Montego
#
# DESCRIPTION: Program to compute and print 100th prime number.
#
#-------------------------#
# Problem 1
prime = 3
div = 2
count = 1
while count<1000:
while div<prime:
if prime%div == 0:
div = prime+1
else: div = div+1
if div == prime:
count+=1
prime+=2
div=2
print (prime-2)
#---------------------------#
# Problem 2
#
# Author: Montego
#
#---------------------------#
import math
prime = 3
div = 2
n = 1000
logsum = math.log(2)
while prime<n-1:
while div<prime:
if prime%div == 0:
div = prime+1
else: div = div+1
if div == prime:
logsum+= math.log(prime)
prime+=2
div=2
print (logsum)
print (n)
print (logsum/n)
No comments. Sign up or log in to comment import math
def prime(x):
for i in range(2,x):
if x%i == 0:
return None
return x
def findprime(n):
pl = [2]
i = 3
while len(pl)<n:
if prime(i)!= None:
pl.append(prime(i))
i += 2
return pl[n-1]
def ratio(n):
sumlog = 0
for i in range(1,n):
sumlog = sumlog + math.log(findprime(i))
print(findprime(n))
print(sumlog)
return sumlog/findprime(n)
print (ratio(100))
No comments. Sign up or log in to comment I had to cheat a little bit with this code, couldn't take not knowing the answer. I don't remember seeing a lot of these concepts in the video, guess I need to do more reading. number = int(raw_input("How many prime numbers would you like me to count? "))
counter = 1
prime = 3
while counter < number:
divisor = prime/2
while divisor > 1:
if prime % divisor == 0:
prime = prime + 2
divisor = prime / 2
else: divisor = divisor - 1
counter = counter + 1
prime = prime + 2
print "If you count", number, "prime numbers you will arive at %s." % (prime-2)
No comments. Sign up or log in to comment ifprime=2
divisor=2
counter=0
while (counter<1000):
if divisor<ifprime:
if (ifprime%divisor==0):
ifprime=ifprime+1
divisor=2
else:
divisor=divisor+1
else:
counter=counter+1
if counter<1000:
ifprime=ifprime+1
divisor=2
print 'the 1000th prime is',ifprime
#problem 2
from math import *
ifprime=3
divisor=2
counter=0
sum=0
n=100
while (counter<1000):
if divisor<ifprime:
if (ifprime%divisor==0):
ifprime=ifprime+1
divisor=2
else:
divisor=divisor+1
else:
sum=sum+log(n)
counter=counter+1
if counter<n:
ifprime=ifprime+1
divisor=2
ratio = float(sum)/float(n)
print 'this is the number',n
print 'this is the sum',sum
print 'this is the ratio',ratio
print 'this is the counter',counter
No comments. Sign up or log in to comment ps1 ##Program to find the 1000th prime number
##Problem 1
#Initialize Variables
prime = 3
isprime = 2
counter = 1
#Loop to count to the 1000th prime number
while(counter < 1000):
#Check that divisor is less than the number being checked
if ( isprime < prime):
#Check if the nummber is prime
if(prime%isprime == 0):
prime = prime + 1
isprime = 2
else:
isprime = isprime + 1
else:
#If it is, add one to the counter, and reset the isprime variable
counter = counter + 1
if(counter < 1000):
prime = prime + 1
isprime = 2
#Print the 1000th prime.
print prime
##Problem 2
from math import *
prime = 3
isprime = 2
counter = 1
total = 0
n = input('Enter a number ')
while(counter < n):
if ( isprime < prime):
if(prime%isprime == 0):
prime = prime + 1
isprime = 2
else:
isprime = isprime + 1
else:
total = total + log(prime)
counter = counter + 1
if(counter < n):
prime = prime + 1
isprime = 2
ratio = float(total)/float(n)
print 'The number you entered is ', n
print 'The total of all the log functions is ', total
print 'The ratio is ', ratio
No comments. Sign up or log in to comment Problem Set 1 (Lesson 2, assignment 1)import math prime = 3 count = 1 divisor = 2 while count<1000: while divisor<prime: if prime%divisor == 0: divisor=prime+1 else: divisor += 1 if divisor == prime: count += 1 prime += 1 divisor=2 print 'Your 1000th prime is: ',prime-1 No comments. Sign up or log in to comment #Problem 1
prime=3
div=2
count=1
while count<1000:
while div<prime:
if prime%div!=0:
div=div+1
elif prime%div==0 and prime!=div:
count=count
prime=prime+2
div=2
if prime%div==0 and prime==div:
count=count+1
div=2
if count!=1000:
prime=prime+2
if count==1000:
print prime
#Problem 2
from math import *
odd=3
div=2
count=1
logsum=log(2)
whichprime=int(raw_input("n="))
if whichprime==1:
print "sum of logs: " + str(logsum)
print "nth prime: " + str (2)
print "ratio: " + str(logsum/2)
elif whichprime!=1:
while count<whichprime:
while div<odd:
if odd%div!=0:
div=div+1
elif odd%div==0 and odd!=div:
count=count
odd=odd+2
div=2
if odd%div==0 and odd==div:
count=count+1
div=2
logsum=logsum+log(odd)
if count!=whichprime:
odd=odd+2
if count==whichprime:
print "sum of logs: " + str(logsum)
print "nth prime: " + str(odd)
print "ratio: " + str(logsum/odd)
No comments. Sign up or log in to comment #Problem 1
n=int(raw_input("insert which prime you want to know:"))
pres=2
count=1
div=2
while count<=n : # count prime numbers up to n
while pres/2>div : #check if divides to numbers up to half current
if pres%div==0 :
div=pres+1 #not a prime, make divisor to be false on next conditions
else:
div+=1 #check next number as divisor
if pres>=div:
count+=1 #prime, count one up
prime=pres
if pres==2: #special case of 2
pres+=1
else:
pres+=2 #3 and up, check through odd numbers only
div=2 #reset divisor to 2
print "The ",n,"prime no. is ",prime #print the n prime
-------------------
#Problem 2
import math
n=int(raw_input("which n to sum up to:"))
pres=2
div=2
sum=0
while pres<=n : # count prime numbers up to n
while pres/2>div : #check if divides to numbers up to half current
if pres%div==0 :
div=pres+1 #not a prime, make divisor to be false on next conditions
else:
div+=1 #check next number as divisor
if pres>=div:
prime=pres #current number is a prime, find log and add to sum
pl=math.log(prime)
sum+=pl
if pres==2: #special case of 2
pres+=1
else:
pres+=2 #3 and up, check through odd numbers only
div=2 #reset divisor to 2
print "The sum of the logs of the primes is ",sum
print "The number n is ",n
ratio=sum/n
print "The ratio of the two above is ",ratio
No comments. Sign up or log in to comment Assignment 1 # Problem Set 1
# Name: jimmy
# Collaborators: 0
# Time: Atleast 4 days
#Part A
count = 1
prime = 3
while count < 1000:
divider = prime/2
while divider > 1:
if prime%divider==0:
prime = prime + 2
divider = prime / 2
else: divider = divider - 1
count = count + 1
prime = prime + 2
print "Prime Number", prime-2, "Counter is", count
#Part B
import math
prime=3
counter=1
n=int(raw_input("enter a number "))
sum_logs=math.log(2)
while prime<n:
divisor=3
while (divisor<math.sqrt(prime) and prime%divisor <> 0):
divisor=divisor+2
if divisor > math.sqrt(prime):
sum_logs = sum_logs + math.log(prime)
prime=prime+2
print sum_logs
print prime
ratio=sum_logs/prime
print ratio
No comments. Sign up or log in to comment #Problem Set 1
#Michael
prime = 3
count = 1
divisor = 2
while count<1000:
while divisor<prime:
if prime%divisor == 0:
divisor = prime+1
else: divisor = divisor+1
if divisor == prime:
count+=1 #same as count=count+1
prime+=2
divisor=2
print 'The 1000th prime is: ',prime-2
from math import*
prime = 3
divisor = 2
n = 1000
logsum = log(2)
while prime<n-1:
while divisor<prime:
if prime%divisor == 0:
divisor = prime+1
else: divisor = divisor+1
if divisor == prime:
logsum+=log(prime)
prime+=2
divisor=2
print 'The sum of the logarithms of all the primes less than n is ', logsum
print 'The number n is ', n
print 'The ratio of the sum of the logarithms to n is ', logsum/n
No comments. Sign up or log in to comment #!/usr/bin/env python
#
# Problem Set 1a
#
# A program that computes and prints the 1000th prime number.
# Finds primes using trial division (least efficient method)
#------------------------------------------------------------
prime_count = 0
n = 2
while (prime_count <= 1000):
#if even, check for 2, the only even prime
if (n % 2 == 0):
if n == 2:
prime_count += 1
n += 1
else:
# number is odd, possible prime
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
n += 1
break
else:
# prime!
prime_count += 1
if prime_count == 1000:
print "The 1000 prime is", n
else:
n += 1
#!/usr/bin/env python
#
# Problem Set 1b
# A program that computes the sum of the logarithms of all the
# primes from 2 to n, prints out the sum of logs, n, and the
# ratio of both.
#
#------------------------------------------------------------
from math import log
logs = 0
limit = input("Enter a number: ")
limit += 1
for n in range(2, limit):
#if even, check for 2, the only even prime
if (n % 2 == 0):
if n == 2:
logs += log(n)
else:
# number is odd, possible prime
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
break
else:
# prime!
logs += log(n)
print "Sum of logs of the primes = ", logs
print "n = ", n
print "ratio = ", (float(logs)/float(n))
No comments. Sign up or log in to comment # Problem Set 1
# Name: TheHedge
# Collaborators: 0
# Time: ~03:00:00
# Part A
c = 1 # use this to count the number of primes
a = 3 # test value, starting at 3 as 1 & 2 are primes
d = 1000 # set the number of the prime we want
while (c < d): # only run if the # of primes is less than d
b = a/2 # what is the remainder if divided by 2?
while (b > 1): # if there is no remainder, its not a prime
if a % b == 0: # if it is not a prime...
a = a + 2 # set a to the next odd number
b = a / 2 # what is the remainder if divided by 2?
else: b = b - 1 # a is a prime, so
c = c + 1 # increase the count of primes by 1
a = a + 2 # go to the next odd number
print a - 2 # now that the 1000th prime is known, show its value
# Part B
import math # get the math tools
a = 3
c = 1 # counter
d = int (raw_input("Enter a Number: ")) # user inputs a value
e = math.log(2) # the log of 2, the starting point
while a < d: # only run when primes are less than d
b = 3 # we start with 3
while (b < math.sqrt(a) and a % b <> 0): # do this for values where b < sqrt(a) and for primes
b = b + 2 # set b to the next
if b > math.sqrt(a):
e = e + math.log(a) # add the log of a to e
a = a + 2 # go to the next odd number
print e # the sum of the logs of the primes
print a # the number chosen
r = e / a # calculate the ratio of e to a
print r # print the ratio of e to a
No comments. Sign up or log in to comment Assignment 1 parts a and b Part A
y = 1
z = 3
while (y < 1000):
x = z/2
while (x > 1):
if z % x == 0:
z = z + 2
x = z / 2
else: x = x - 1
y = y + 1
z = z + 2
print z - 2
Part B
import math
x = 3
y = 1
z = int (raw_input("Please Enter a Number"))
u = math.log(2)
while x < z:
v = 3
while (v < math.sqrt(x) and x%v <> 0):
v = v + 2
if v > math.sqrt(x):
u = u + math.log(x)
x = x + 2
print u
print x
w = u / x
print w
No comments. Sign up or log in to comment I defined problem 1a as a function for an simple solution to problem 1b. to get the 1000th prime simply type prime(1000) # Problem Set 1
# Name: Fredrik Gustafsson
# Python version: 3.2
# Time: 1:00
##
## Problem 1a
##
def prime(number):
prime_cand = 1 # Prime candidates
prime_count = 1 # Prime counter
if number == 1:
return(2)
while prime_count < number:
# Variables needed for the prime test
x = 2
y = 1
prime_cand += 2
# Multiplies all the remainders of prime_cand/x for x in: 1 < x < prime_cand/2
while x < (prime_cand / 2):
y = y * (prime_cand % x)
x += 1
# If the product of the remainders is zero then prime_cand is evenly divided by
# some value x for x in 1 < x < prime_cand/2, hence prime_cand is not a prime.
if y != 0:
prime_count += 1
return(prime_cand)
##
## Problem 1b
##
import math
n = int(input("Please input n: "))
su = 0
x = 1
while prime(x) < n:
su = su + math.log(prime(x))
x += 1
print ("The sum of the logarithms of the all primes < n is:", su)
print ("the number n is:", n)
print ("and finaly the ratio log(...) / n is:", su / n)
No comments. Sign up or log in to comment This is my solution for Problem 1 but the output gives me "7927" which is the 1001th prime prime = 1
count = 1
divisor = prime-2
while count<1000:
prime += 2
divisor = prime-2
while divisor>1:
if prime%divisor == 0:
divisor = 0
else :divisor -= 2
if divisor == 1:
count += 1
print 'The 1000th prime is', prime
Comments:I know I can solve it by initializing count = 2, but this makes no sense ##Problem 1a
prime_counter=1 #How many prime numbers have been found, up to 1000
test_number=3 #Starting prime number
while (prime_counter<1000): #until prime_counter reaches 1000
divisor=test_number/2 #divisor is test_number divided by 2
while (divisor>1): #Do until divisor reaches 1
if test_number%divisor==0: #if remainder of test_number divided by the divisor is 0
test_number=test_number+2 #increase test_number by 2
divisor=test_number/2 #redefine divisor to reflect new test_number
else: divisor=divisor-1 #otherwise decrese divisor by 1
prime_counter=prime_counter+1 #add another prime to the prime_counter, so at 5 prime_counter = 2
test_number=test_number+2 #increase test_number by 2
print test_number-2 #print the last working test_number
##Problem 1b
import math
prime=3
counter=1
n=int(raw_input("enter n"))
sumoflogs=math.log(2)
while prime<n:
divisor=3
while (divisor<math.sqrt(prime) and prime%divisor <> 0):
divisor=divisor+2
if divisor > math.sqrt(prime):
sumoflogs = sumoflogs + math.log(prime)
prime=prime+2
print sumoflogs
print prime
ratio=sumoflogs/prime
print ratio
No comments. Sign up or log in to comment # problem set 1
from time import time
from math import *
import sys
########## Problem 1 ##########
def PrimeNth(n):
"prints out the nth prime number"
primesFound = 0
number = 1
while primesFound < n:
number = number + 1
divisor = 2
isPrime = True
while divisor * divisor <= number:
if number % divisor == 0:
isPrime = False
break
divisor = divisor + 1
if isPrime:
primesFound = primesFound + 1
return number
######## Problem2 ##########
def Prime(n):
"Returns a list containing prime numbers"
primes = []
primesFound = 0
number = 1
while primesFound < n:
number = number + 1
divisor = 2
isPrime = True
while divisor * divisor <= number:
if number % divisor == 0:
isPrime = False
break
divisor = divisor + 1
if isPrime:
primesFound = primesFound + 1
primes.append(number)
return primes
def Log(lst):
sum = 0
for prime in lst:
sum = sum + log(prime)
return sum
def main():
start = time()
print "Problem 1:"
print "The",str(sys.argv[1])+"nth prime number is :", PrimeNth(int(sys.argv[1]))
#print Prime(int(sys.argv[1]))
print "The sum of log of",str(sys.argv[1]),"is: ", Log(Prime(int(sys.argv[1])))
print 'Time in seconds:' + str(time() - start)
if __name__ == '__main__':
main()
No comments. Sign up or log in to comment #problem set 1
#Name Waz
# Problem 1
#Write a program that computes and prints the 1000th prime number.
import math
candidate = 3 #starting from 3
counter = 1 #counting no 2
while counter < 1000:
divisor =3 #no need to start below 3
while (divisor< math.sqrt(candidate) and candidate%divisor <> 0): # test4primality(credit to munia)
divisor = divisor + 2
if divisor > math.sqrt (candidate): #if we find a prime
counter = counter +1 #up the count
candidate= candidate + 2
print candidate-2 #to substract the last 2 added
#Problem 2
#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.
import math
candidate = 3 #starting from 3
counter = 1 #counting no 2
n=int(raw_input("What is your n?"))
sumoflogs=math.log(2) #we start with 2, remember?
while candidate < n:
divisor =3 #no need to start below 3
while (divisor< math.sqrt(candidate) and candidate%divisor <> 0): # test4primality
divisor = divisor + 2
if divisor > math.sqrt (candidate): #if we find a prime
sumoflogs = sumoflogs + math.log(candidate)
candidate= candidate + 2
print sumoflogs
ratio = sumoflogs/candidate
print "Ratio is ", ratio
No comments. Sign up or log in to comment #!/usr/bin/env python
#encoding=utf-8
from math import *
##===============================PROBLEM 1==========================
def cprimo(x):
"""testa se n é um número primo
(Tests if n is a prime number )
"""
if x == 1:
return False
elif x == 2:
return True
elif x%2 == 0:
return False
else:
for i in range(3, int(floor(sqrt(x)))+1 , 2):#só é preciso checar os ímpares até raiz de x. +1 para incluir a raiz de quadrados perfeitos.
#(We only need to verify odd integers up to the sqrt of x! +1 is a trick to account for perfect squares)
if x%i != 0:
pass
else:
#print n, "não é primo."
return False
#print n, "é primo."
return True
def enesimop(n):
"""mostra quem é o n-ésimo número primo
(Shows who is the n_th prime number)"""
countprime = 0
rodada=0
while countprime < n:
rodada = rodada + 1
if cprimo(rodada) == True:
countprime = countprime + 1
else:
pass
if n == countprime:
return rodada
print str(1000)+'-th prime number is:', enesimop(1000)
##========================================PROBLEM 2===============
def listadeprimos(n):
"""lista todos os números primos menores ou iguais a ao n-ésimo primo.
(Lists all prime numbers less or equal to the nth prime.)"""
countprime = 0
rodada=0
lista=[]
while countprime < n:
rodada = rodada + 1
if cprimo(rodada) == True:
lista.append(rodada)
countprime = countprime + 1
else:
pass #I don't know when to use pass or continue. Please comment.
if n == countprime:
return lista
def sumlog(n):
"""Computa a soma dos lagarítmos de todos os números
primos de 2 ao n-ésimo primo e também a taxa entre essa soma e o n-ésimo primo"""
#primomax = enesimop(n)
soma = 0
lista = listadeprimos(n)
for i in lista:
#if cprimo(i) == True:
#print "log of", i, "is", log(i)
#print soma
soma = soma + log(i,e) #Here I am using the natural logarithm instead of the common log_10
#python uses this by default it seems.
#uncomment for portuguese:
#~ print str(n)+"-ésimo primo:", lista[n-1]
#~ print "Soma dos logs dos números primos menores que o", n, "-ésimo primo (", lista[n-1], "):", soma
#~ print "Relação de", n, "-ésimo primo (", lista[n-1], ") sobre a soma dos logarítmos dos primos menores que ele:", lista[n-1]/soma
#~ print "============================================================================="
#uncomment for english:
print str(n)+'-th prime number is', lista[n-1]
print 'The sum of the natural logarithms of prime numbers smaller then the', str(n)+'th prime is:', soma
print 'Ratio of the', str(n)+'-th prime number to that sum:', lista[n-1]/soma
print "============================================================================="
print 'Observe how the ratio aproximates 1 the bigger the number is:'
sumlog(10**3)
sumlog(10**4)
sumlog(10**5)
sumlog(10**6)
No comments. Sign up or log in to comment This is the first real program I've ever made. I think it's efficient, and also lets the user choose the Nth prime number they wish to find, not just the 1000th. ## This program can find the Nth prime number, as input by the user.
## user input section
import string
import math
goal = raw_input("Enter the Nth prime number you wish to find: ")
while str.isdigit(goal) == False:
print "You may only enter integers."
goal = raw_input("Enter the Nth prime number you wish to find: ")
goal = int(goal)
testnumcount = 1
numofprimes = 0
## loop through all required test numbers
while numofprimes < goal+1:
testnum = testnumcount
divisor = 3
prime = 1
looping = True
## check to see if individual test number is prime,
## skipping all even numbers except 2
while looping == True:
if testnum != 2:
if testnum % 2 == 0:
divisor += 1
prime = 0
if testnum % divisor == 0:
if testnum != divisor:
divisor += 1
prime = 0
else:
divisor += 1
## conditions for ending the test
if divisor > math.sqrt(testnum):
looping = False
if prime == 0:
looping = False
## what to do if a prime is found
if prime == 1:
if numofprimes == goal:
print testnum,"is the last prime number in a series of",goal
##print testnum,"is prime."
numofprimes += 1
testnumcount += 1
print "END"
I wrote this program but Python identified an error that I have been struggling to correct. It would be much appreciated if someone could help me identify it. #This program calculates the 1000 prime
count=1
prime=3
divisor=(prime-2)
while(count<1000):
if((prime)%2)!=0:#tests if prime is odd
while (prime%divisor)!=0 and divisor > 1:#tests if number is prime
divisor=divisor-2
if not prime%divisor!=0:#if number is prime
prime+=2#move onto next odd number
count+=1#advance the count
else prime+=2#syntax error identifid by python here!
print("The 1000 prime is", prime)
Comments:if someone could please trake a look at this progra and give feedback on my syntax error that'd be great. I tried adding a colon afterr the 'else' statement which removed the error however the program never produced any output when tried to run it Hi mlevy93, The syntax error is that the else statement requires a colon after the word else. It seems like you were able to fix that. The reason that it never produced output after you fixed it is that it went into an infinite loop. It never leaves the first while statement because 'count' is never incremented. Count and divisor start at 1. The place in your code that increments count is protected by the second while statement where it says that divisor must be greater than one. So your code execution is going like this:
count = 1
prime = 3
divisor = 1
while(count is less than 1000) [This is True]
if(prime % 2 != 0) [This is True]
while .....divisor > 1 [This is False]
Go back to the top and do it all over:
count = 1
prime = 3
divisor = 1
Loop infinitely!
One way that you can debug your code is by printing out your variables to the screen. So, to see if 'count' is changing, you can do this:
while(count<1000):
print count
... rest of your code...
Then once you have fixed the bug, you can remove the print statement.
Hope that helps! This was pretty tough for me. I have zero programming experience and really had to dive in to figure anything out. ##Problem Set 1
##Name: Audie Swan
##Collaborators: me, myself, and I
##Time: took me forever man!
##Problem 1 -
##Write a program that computes and prints the 1000th prime number
import math
primeList = [2]
primeCandidate = 3
divisor = 3
whichPrime = input("Which prime would you like to find, enter 1000 for Problem set 1 answer: ")
while len(primeList) < whichPrime:
if divisor == primeCandidate:
primeList.append(primeCandidate)
primeCandidate += 2
divisor = 3
if primeCandidate % divisor != 0:
divisor += 1
else:
primeCandidate += 2
divisor = 3
print primeList.pop()
##Problem 2 - Sum of log of primes
primeList = [2]
primeCandidate = 3
divisor = 3
maxNumber = input("Enter a maximum number, n, to calculate the sum of the log of all primes less than that number: ")
logPrimeSum = 0
while primeCandidate < maxNumber:
if divisor == primeCandidate:
primeList.append(primeCandidate)
primeCandidate += 2
divisor = 3
if primeCandidate % divisor != 0:
divisor += 1
else:
primeCandidate += 2
divisor = 3
for eachPrime in primeList:
logPrime = math.log(eachPrime)
logPrimeSum += logPrime
print "The max number is", maxNumber
print "The sum of log of primes up to", maxNumber, "is", logPrimeSum
print "logPrimeSum / maxNumber is", logPrimeSum / maxNumber
No comments. Sign up or log in to comment prime = 3
count = 1
divisor = 2
while count<1000:
while divisor<prime:
if prime%divisor == 0:
divisor=prime+1
else: divisor += 1
if divisor == prime:
count += 1
prime += 1
divisor=2
print 'the 1000th prime is: ',prime-1
No comments. Sign up or log in to comment from math import *
def prime_counter():
odd = 1
max = 1
l = log(2)
n = raw_input('How many primes to count to?', )
while max <= int(n): #Sets up main loop
odd += 2 #incriments odd by 2 every new loop
for x in range(2, odd): #sets up loop with current odd value as range limit
non_zero = (odd % x) #uses current position in range (x) as modulus value
if non_zero is 0: #if there is no remainder its not prime
break #go to next number in max range
else: #if there is a remainder
continue #go to next number in x range
else: #if prime
print odd #print odd
max += 1 #incriment main loop by 1
l = l + log(odd)
else:
print 'max prime ' + str(odd)
print l
print (float(l)/float(n))
prime_counter()
No comments. Sign up or log in to comment # Problem Set 1
# Name: ariel0
# Collaborators:
# Time: 10:10
#
n_primo=1
limite=1000
candidato=1
while(n_primo<limite):
#initialize the candidate
candidato=candidato+2
#check the candidate
i=2
es_primo=True
while(i*i<=candidato):
if(candidato%i==0):
es_primo=False
break
i=i+1
if(es_primo==True):
n_primo=n_primo+1
print "The " +str(n_primo)+"th prime number is: "+str(candidato)
# Problem Set 1
# Name: ariel0
# Collaborators:
# Time: 40:20
#
from math import *
n=int(raw_input("Enter a value for n:"))
suma=0
for j in range(2,n):
if(j==2 or j==3):
es_primo=True
else:
if(j%2<>0):
i=2
es_primo=True
while(i*i<=j):
if(j%i==0):
es_primo=False
break
i=i+1
else:
es_primo=False
if(es_primo==True):
suma=suma+log(j)
j=j+1
print "Value of n: "+str(n)
print "Sum of the logarithms: "+str(suma)
print "Ratio: "+str(suma/n)
No comments. Sign up or log in to comment I'm satisfied with the work I did in problem 1, but I feel like I could have come up with a more elegant way to deal with the first prime (2) which doesn't fit with the other rules I made. This was very challenging, especially so early on in the course! I'm not sure if I solved problem 2 correctly because I allow a value for n that may not be a prime number. Criticism and advice is welcomed :)
# Problem Set 1
# Problem 1
# Name: 4orty4
# Time: 2:00
# This program will calculate the 1000th prime number.
# 2 is the first prime number.
# First I need to generate odd numbers to test, since
# all primes except 2 are odd. This means that I will
# begin the prime counter at 1
# A positive number, x, is prime if:
# x/n=(int) only where x=n (n>1)
# or x%n=0 only where x=n (n>1)
candidate = 1 # 3 will be the first tested number
divisor = 2
primecounter = 1
# initial state for number of primes found (because 2 already known prime)
# +1 for each prime found, up to 1000
while primecounter < 1000:
candidate = candidate + 2 # The next odd number is tested
divisor = 2
isnotprime = 0 #this will flip to 1 if a divisor is found
while divisor <= (candidate/2) and isnotprime == 0:
if candidate%divisor == 0:
isnotprime = 1 #a divisor is found so this while statement stops
else:
divisor = divisor + 1 #the loop is tried with a new divisor
# The while loop continues until either the largest allowable divisor
# has been tried, or the candidate is proven to not be prime.
if isnotprime == 0: # 0 result means the number is prime
primecounter = primecounter + 1
print 'The 1000th prime number is', candidate
# Problem Set 1
# Problem 2
# Name: 4orty4
# Time: 1:00
# This program will calculate the sum of the natural logs
# of all primes less than n.
# It will print n, the sum, and the ratio of sum/n
# It differs from the first part of the assignment
# because the caluclation stops when the prime is less
# than a given number, rather than stopping when the 1000th
# prime number is found.
from math import *
n = int(raw_input('Select n: the maximum value of the last prime:'))
# Converts input from str to int
logsum = log(2) # Initializes the logsum value to the log of 2
candidate = 1 # 3 will be the first number tested
divisor = 2 # first divisor to test is 2
primecounter = 1 # 2 already known as prime
while candidate < n: # Loop stops when
candidate = candidate + 2 # The next odd number is tested
divisor = 2 #reset divisor to 2
isnotprime = 0 #this will flip to 1 if a divisor is found
while divisor <= (candidate/2) and isnotprime == 0:
if candidate%divisor == 0:
isnotprime = 1 #a divisor is found so this while statement stops
else:
divisor = divisor + 1 #the loop is tried with a new divisor
if isnotprime == 0: # 0 result means the number is prime
logsum = logsum + log(candidate)
##primecounter = primecounter + 1
print 'The n you selected is', n,'\n'
print 'The sum of the logarithms for all primes less than',n,'is',logsum,'\n'
print 'The ratio of the sum to n is',logsum/n
Comments:A quick question-- I noticed that most other solutions make use of the "def" operator. I'm having a hard time working out how these fit in to the program. Is this covered in future lessons, or should I get a handle on it before continuing? The "def" operator, as you call it, is the keyword to begin a function definition. It is discussed later and is available in the python tutorial. btw, to find if a number is prime you only need to divide it by the odd numbers from 3 to the square root of the number. It'll go a lot faster that way. And the modulus operator % returns the remainder of a division, e.g., 3 % 2 = 1. Hope this helps. g It seems obvious now, but I didn't realize how far overboard I went with testing divisors. It might go even faster by using only previously found primes between 3 and the square root as the divisor, although I'm not sure my programming is up to that yet. I'll revisit this once I've learned more. Thanks for taking the time to give me some pointers! Prime Numbers Assignment# Amy Karoline
# Course 600
# Problem Set 1a & b, Primes
# Prime Numbers are not divisible by anything but 1 and itself
# Time: Part 1: 4.5 hours; Part 2: 1.5 hours
# 01222011
####
from math import *
#Part A
primes = [2]
x=1000
testNum = 3
z=0
while len(primes) < x :
notPrime = 0
divider = 3
while (divider < (testNum/2)):
if testNum % divider == 0:
notPrime = 1
divider += 1
if notPrime == 0:
primes.append(testNum)
testNum += 2
print primes[x-1]
#Part B
#log(a)x = N means that a^N = x
#log x means log(10)x (common log)
#ln x means log(e)x, e is 2.718... (natural log)
##Rules of logs:
##Inverse: log(a)a^x = x and a^(log(a)x) = x
##Product: log(a)(xy) = log(a)x + log(a)y
##Quotient: log(a)(x/y) = log(a)x = log(a)y
##Power: log(a)(x^p) = p * log(a)x
##Change of base formula: log(a)x = log(b)x/log(b)a
##for sufficiently large n, the product of primes less than n is less than or
##equal to e^n and as n grows, the (product of the primes)/e^n
##gets close to 1
##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.
n = None
while not n:
try:
n = int(raw_input('Please define n: '))
except ValueError:
print 'Invalid Number'
#now compute all primes between 2 and n
primesToN = [2]
testNumB = 3
while testNumB <= n:
dividerB = 3
notPrimeB = 0
while dividerB < (testNumB / 2):
if testNumB % dividerB == 0:
notPrimeB = 1
dividerB += 1
if notPrimeB == 0:
primesToN.append(testNumB)
testNumB += 2
print 'Primes found: ', primesToN
primesCount = 0
logSum = 0
while primesCount < len(primesToN):
logSum += log(primesToN[primesCount])
primesCount += 1
print 'logSum: ', logSum
print 'n: ', n
print 'Ratio: ', logSum/n
No comments. Sign up or log in to comment # Problem 1
#
# Write a program that computes and prints out the 1000th prime number
from math import *
def isPrime(number):
"""
Determines whether 'number' is prime or not.
"""
# Guard clauses
if 1 >= number: return False
elif 2 == number: return True
divisor = 2
# Only need to try divisors less than half of 'number'
# as
#
# number / divisor
# for all: (number / 2) < divisor < number
#
# will never divide evenly
while divisor < number // 2:
if 0 == number % divisor: return False
divisor += 1
return True
primeCounter = 1
current = 3
print "Found Prime: #1: 2"
while (primeCounter < 1000):
if isPrime(current):
primeCounter += 1
print "Found Prime: #%d: %d" % (primeCounter, current)
current += 2
# Problem 2
#
# Write a program that prints the sum of log(x) where x is every prime number less than n.
# It should also print out the number n and the ratio of these two quantities.
from math import *
n = 500
current = 3
primeLogSum = log(2)
while current <= n:
if isPrime(current):
primeLogSum += log(current)
current += 2
print "Sum of logarithms: %s" % str(primeLogSum)
print "n: %s" % str(n)
print "ratio: %s" % str(primeLogSum / n)
No comments. Sign up or log in to comment Assignment #1: Part 1 - Print the 1000th prime number Part 2 - Show that the ratio of the sum of log of primes < N and N approaches 1 as N gets larger
# Assignment #1 Part #1 - compute and print the 1000th prime number
# -----------------------------------------------------------------
# Assignment #1 - function to see if a number is prime
def isPrime(value):
if value == 1: return False
if value == 2: return True
for i in range(3,value / 2,2):
if (value % i) == 0:
return False
return True
# initilize the necessary variables
found = False # tells us when to stop the loop
candidate = 3 # the initial value we are checking to see if it is prime
count = 1 # the count of prime numbers we've found, start at 1 because 2 is a prime
# continue until we've found 1000 primes
while( found == False ):
if isPrime(candidate) == True: # loop thru all odd numbers less than half the candidate
count += 1 # increment out counter of found prime numbers
if count == 1000: # did we find our 1000 hit?
print 'The 1000 prime number is:', candidate, '\n'
found = True
else:
candidate += 2 # increment our candidate and try again
# Assignment #1 Part #2 - Sum of log of primes < N and N ratio approaches 1 as N gets larger
import math
userValue = int(raw_input('Enter your value to calculate: '))
sumLogs = 0.0
for i in range(1,userValue,2):
if isPrime(i) == True:
sumLogs += math.log(i)
print '\nThe sum of the logs of the prime values less than', userValue, 'is:', sumLogs
print 'The ratio is:', sumLogs / userValue
No comments. Sign up or log in to comment Compute primes. Compute sum of log of primes and divide by largest prime. And print out some data. Please comment. #Program Number One
import math
def prime(max):
sum = [math.log(2), 1, 1]
while sum[2] < max:
sum[1] += 2
for divisor in range(3, int(math.sqrt(sum[1])+1)):
if sum[1]%divisor == 0: break
else:
sum[2] += 1
sum[0] += math.log(sum[1])
return sum
data = prime(1000)
print data[1], 'is prime number: ', data[2]
#Program Number Two
number = int(raw_input("Please enter an integer: "))
data = prime(number)
print data[0], 'is the sum of the logs of all the primes to', data[1]
print data[1], 'is prime number', data[2]
print data[0] / data[1], 'is the ratio'
Comments:Your solution for problem one is correct. However, I'm not sure if problem two is correct. I'd recommend breaking the problem up into separate functions. Since you use one function that stores an array, it looks like it's complicating things. Instead, have the functions accept a scalar value and return a scalar value. If it requires looping through a range multiple times, that's fine. Clarity and readability are important too. For number two, I expect f(100) = 0.837, and f(1000) = 0.956. Hope that helps. I looked at the directions and may have misread them the first time. I thought it meant to print out the nth prime not the primes up to n. I am using an array to return more than one value at one time. 7919 is prime number: 1000 Please enter an integer: 1000 7812.28354073 is the sum of the logs of all the primes to 7919 7919 is prime number 1000 0.986523998072 is the ratio First of all I tried to do this problem set without the use of lists, wich made it a bit harder. I definitely need some feedback because some things should still change: -Haven't implemented the prime_test to stop at lower counts than prime_number itself (could use the sqroot as seen in the other examples) -didn't check if a number is prime, just made it so that it picked a prime lower than the given one if last_prime!= a prime number that is all I can think of now, feedback very much apreciated! edit: Switched code and coment #import
from math import *
#variables
prime_number=2 #start with 2 as prime number
prime_count=1 #prime_count gives us the prime number we have (should end at 1000?), or 1001 in our test
sum_of_primes=0
#definitions (not seen yet in course so trying to put this into the program itself,turns out it's harder than I thought...
def prime_test(prime_number):
for number in range(2,prime_number): #replace by prime_number-1 again and see if better
if prime_number%number ==0:
if number!=prime_number and number !=1:
return False
return True
#user input
end_count=raw_input('how many prime numbers do you want to generate?\n> ')#should be 1000 for problem1
end_count=int(end_count)+1 #add 1 to end at the right number, better way?
last_prime=raw_input('what is the last prime you want to count the logs?')#represents the 'n' from problem2
last_prime=int(last_prime)
#program part
print 'starting to generate prime numbers \n' #beauty
print '*'*40,'\n' # s'more beauty
while prime_count != end_count: #wait till nth item
if prime_test(prime_number) == True:
print 'prime number', prime_count,'=', prime_number
if prime_number <= last_prime: #part of problem2, adds logs until prime number equals n
sum_of_primes+=log(prime_number)
last_real_prime=prime_number #the real last prime, not the one you chose (this one will be lower)
prime_number+=1 #+2 would be better but that would skip 2
prime_count+=1
else:
prime_number+=1
print '*'*40,'\nall prime numbers untill count',(prime_count-1),'are given'
print '*'*40,'\n'
print 'your last prime was:',last_real_prime,'the sum of the log of all the primes=',sum_of_primes,'the ratio=',sum_of_primes/last_prime
#wait for user
raw_input('press any key to end')
Comments:Here's some feedback on problem #1. The hints section of the assignment, in step 2, they say to generate all odd integers greater than 1. Obviously, you can't go to infinity, but python does allow a third parameter to the range function that will generate only odd numbers: >>> n = 10 >>> range(3,n,2) [3, 5, 7, 9] # Problem Set 1
from math import *
# pt. 1
primelist = [2]
candnum = 3
primecount = 1000
while len(primelist) < primecount :
cantbeprime = 0
for i in range (len(primelist)) :
if candnum % primelist[i] == 0 :
cantbeprime = 1
if cantbeprime == 0 :
primelist.append(candnum)
candnum += 2
print "The 1000th prime number is", str(primelist[primecount - 1])
# pt. 2
primelist = [2]
candnum = 3
lptotal = 0
x = raw_input ("Enter upper bound (n): ")
primecount = int(x)
while len(primelist) < primecount :
cantbeprime = 0
for i in range (len(primelist)) :
if candnum % primelist[i] == 0 :
cantbeprime = 1
if cantbeprime == 0 :
primelist.append(candnum)
candnum += 2
for i in range(primecount) :
lptotal += log(primelist[i])
print "Sum of the logs of the primes:", lptotal
print "Number of primes:", primecount
print "Ratio:", lptotal / primecount
No comments. Sign up or log in to comment from math import log
from math import *
print("Begin solving Problem 1.")
def isItPrime(numberToCheck):
for n in range(2,numberToCheck):
if numberToCheck%n == 0 :
return False
return True
primes = []
primeCounter=0;
numbers = 2
while True:
if numbers == 2 or isItPrime(numbers):
primes.append(numbers)
primeCounter += 1
if primeCounter == 1000:
#solution to problem 1
print("The thousandth prime is", numbers)
break
numbers += 1
print("\nBegin solving Problem 2.")
targetN=int(input("What is the target N? "))
totalLog = 0
for numbers in range(2,targetN,1):
if numbers == 2 or isItPrime(numbers):
totalLog += log(numbers)
#solution to problem 2
print("Sum of Log of Primes up til N is ",totalLog)
print("N is ", targetN)
print("ratio of Sum of Log of Primes to N is ", totalLog/targetN)
No comments. Sign up or log in to comment This was a sizable jump from the first assignment. # Problem Set 1
# Name: Jaioxung
# Collaborators: none
# Time: ?
#
## PROBLEM 1 ##
n = 3
prime_number_list = [2]
def is_prime(n):
x = 2
while n % x != 0:
x += 1
if x == n:
return True
while len(prime_number_list) <= 999:
if is_prime(n):
prime_number_list.append(n)
n += 1
print "The 1000th prime is:", prime_number_list[-1]
## PROBLEM 2##
from math import *
n = 3
prime_number_list = [2]
length_of_prime_number_list = 1000
input_number = 10
## Determine if a number is prime
def is_prime(n):
x = 2
while n % x != 0:
x += 1
if x == n:
return True
## Create the list of prime numbers
while len(prime_number_list) <= length_of_prime_number_list:
if is_prime(n):
prime_number_list.append(n)
n += 1
while input_number < prime_number_list[-1]:
sum_of_logs = 0
for item in prime_number_list:
if item <= input_number:
x = log(item)
sum_of_logs += x
input_number +=10
print"------------------------"
print "Number:", input_number
print "Sum of logs of primes less than input number:", sum_of_logs
print "Ratio:", sum_of_logs/input_number
print"------------------------"
No comments. Sign up or log in to comment # Problem Set 1a
# Name: Chris Coe
# Collaborators: OpenStudy help
# Time: 1:50
#
# Program to compute and prints the 1000th prime number
prime = 3 #first prime that isn't 2 or 0...
count = 1
divisor = 2 #first even
while count<1000:
while divisor<prime: #this loop determines if it can be
#divided by a number other than itself
if prime%divisor == 0:
divisor=prime+1
else: divisor += 1
if divisor == prime: #when prime and divisor are =, it means
#that prime is only divisible by itself and 1
#so we increase count to increase our main
#once.
count += 1
#print prime
prime += 1 #we then need to add 1 to prime or it will be
#stuck at the same value forever
divisor=2 #need to reset divisor for each number we are
#testing.
print 'the 1000th prime is: ',prime-1 #prime will be the 1001st prime #
#because prime+=1 is calc. again during
#the last counter loop iteration
#==============================================
# Problem Set 1b
# Name: Chris Coe
# Collaborators: OpenStudy help
# Time: 30 min
#
# Program to compute sum of logs of all primes from 2 to some number n
# Print out the sum of the logs of the primes, the number n, and the ratio
# of these two quantities
from math import *
prime = 3 #first prime that isn't 2 or 0...
count = 1
divisor = 2 #first even
logSums = log(2) # need to include log(2) since the prime = 3 to start
numberN = int(raw_input('Please enter a max number for n: '))
while count<numberN:
while divisor<prime:
if prime%divisor == 0:
divisor=prime+1
else: divisor += 1
if divisor == prime:
count += 1
if prime<numberN:
logSums += log(prime) #take log(prime) and add it to what is in logSums
prime += 1
divisor=2
print 'n: ',numberN
print 'Sum of the logs of the prime #\'s: ', logSums
print 'Ratio of Sum of logs to value n: ', logSums/numberN
No comments. Sign up or log in to comment #Problem 1
primes = 0
x = 2
y = 2
while primes < 1000 and y <= x:
if x%y == 0 and x != y: #Then NOT Prime
y = 2
x = x + 1
elif x == y: #Then PRIME
print x
primes = primes + 1
y = 2
x = x + 1
else: #Continue Testing
y = y + 1
# Problem 2
from math import *
primes = 0
x = 2
y = 2
sum = 0
while primes <= 1000 and y <= x:
if x%y == 0 and x != y: #Then NOT Prime
y = 2
x = x + 1
elif x == y: #Then PRIME
n = x
y = 2
x = x + 1
primes = primes + 1
if n <= 1000:
sum = sum + log(n)
n = n + 1
print sum
else: #Continue Testing
y = y + 1
No comments. Sign up or log in to comment ##Problem #1
#This program computes and prints prime numbers
#The first part generate odd numbers > 1
num = 2
odds = ()
while num < 10000:
if num%2 == 0:
num = num + 1
else:
odds += (num,)
num = num + 1
#The second part is meant to test the subset odds and sort primes into
#the tuple "primes'
primes = (2,) #These are the state variables that start the loop
prime = True
for i in odds: #Here I want to run through all of the numbers in odds
for g in primes: #and divide each odd by all the numbers in the primes list
if i%g ==0:
prime = False #If the test finds the number not to be prime it marks it false
if prime == True: #If the number is prime it will test if the lenght of primes is < 1000
if len(primes) < 1000: #If not it will add the number to primes, if yes it will break the loop
primes += (i,)
else:
break
else:
prime = True #This will reset the prime variable
print 'The 1000th prime is: %d' % primes[-1]
##Problem #2
from math import *
n = input('Please enter the number of primes you wish to sum: ')
num = 2
odds = ()
while num < 10*n:
if num%2 == 0:
num = num + 1
else:
odds += (num,)
num = num + 1
#The second part is meant to test the subset odds and sort primes into
#the tuple "primes'
primes = (2,)
logprimes = (log(2),)
prime = True
for i in odds:
for g in primes:
if i%g ==0:
prime = False
if prime == True: #If the number is prime it will test if the lenght of primes is < n
if len(primes) < n: #If not it will add the number to primes, if yes it will break the loop
primes += (i,)
logprimes += (log(i),)
else:
break
else:
prime = True
sumlogprimes = sum(logprimes[0:-1]) #I wish to comput the sum of log(prime) and the ratio
ratio = sumlogprimes/primes[-1] #of n to the sum of log(prime)
print 'The prime to which you chose to sum is: %d' % primes[-2]
print 'The prime you wish to compare it to is: %d' % primes[-1]
print 'The sum of log(prime) is: ' + str(sumlogprimes)
print 'The ratio of the sum log(prime) to N is: ' + str(ratio)
No comments. Sign up or log in to comment #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
No comments. Sign up or log in to comment ###PS1a###
#print 2, because it is exceptional in being the only even (non-odd) prime
print '{0:4d} {1:4d}'.format(1, 2)
numPrimesCalcd = 1 #because we already printed '2'
candidate = 3 #the first number to test
divTest = 3 #the minimum number a given prime might divide by
while numPrimesCalcd < 1000 :
while divTest <= candidate :
if divTest == candidate :
# It's a prime, because it hasn't divided by anything until it divided by itself
numPrimesCalcd += 1
print '{0:4d} {1:4d}'.format(numPrimesCalcd, candidate)
divTest = 3 #reset divTest to lowest possible divisor
candidate += 2 #skip even numbers
elif candidate%divTest == 0 :
# Not a prime, because it divides by a number other than itself
divTest = 3 #reset divTest to lowest possible divisor
candidate += 2 #skip even numbers
break #break out of the while loop, start testing a new candidate
else :
# Haven't proved or disproved, test with the next odd number
divTest += 2
###PS1b###
from math import *
numPrimesCalcd = 1 #because we include '2' manually
candidate = 3 #the first number to test
divTest = 3 #the minimum number a given prime might divide by
sumOfPrimesLog = log(2) #b/c we already counted 2 manually
while numPrimesCalcd < 1000 :
while divTest <= candidate :
if divTest == candidate :
# It's a prime, because it hasn't divided by anything until it divided by itself
numPrimesCalcd += 1
print sumOfPrimesLog/candidate
sumOfPrimesLog += log(candidate)
divTest = 3
candidate += 2 #skip even numbers
elif candidate%divTest == 0 :
# Not a prime, because it divides by a number other than itself
divTest = 3 #reset divTest to lowest possible divisor
candidate += 2 #skip even numbers
break #break out of the while loop, start testing a new candidate
else :
divTest += 2
No comments. Sign up or log in to comment # Problem Set 1a
# Name: Matthew Coley
# Collaborators:
# Time: 1:00
#
testNumber = 1
primeCounter = 1
testCounter = 2
primeTester = 0
while primeCounter < 1000:
testNumber = testNumber + 2
while testCounter < (testNumber/2):
if testNumber % testCounter == 0:
print "divisible by", testCounter
primeTester = primeTester + 1
testCounter = testCounter + 1
if primeTester == 0:
primeCounter = primeCounter + 1
print testNumber, "is a prime number"
primeTester = 0
testCounter = 2
#testNumber = testNumber + 2
print testNumber, "is the 1000th prime"
# Problem Set 1b
# Name: Matthew Coley
# Collaborators:
# Time: :30
#
testNumber = 1
primeCounter = 1
testCounter = 2
primeTester = 0
sumLogPrime = 0
# Loop until 100 primes are found
while primeCounter < 100:
# Skip even numbers
testNumber = testNumber + 2
# Test all odds divisibility up to half the number
while testCounter < (testNumber/2):
if testNumber % testCounter == 0:
# Incriment primeTester each time a number is divisible
primeTester = primeTester + 1
testCounter = testCounter + 1
# If no numbers were divisible, testNumber is prime
if primeTester == 0:
primeCounter = primeCounter + 1
sumLogPrime = sumLogPrime + log(testNumber)
# Reset counter values
primeTester = 0
testCounter = 2
# Add log of 2, since it was skipped
sumLogPrime = sumLogPrime + log(2)
print sumLogPrime, testNumber, (sumLogPrime / testNumber)
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
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
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)
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
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
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
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)
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))
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)
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
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
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)
Comments:You may want to check problem #1 again. Your solution is printing 7643 as the 1000th prime, but that's not correct. 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)
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
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
No comments. Sign up or log in to comment # 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
Comments:A couple quick thoughts on this HW, jspash. First, the your_number = 12 line should probably be: "your_number = int(raw_input('Enter number for test:'))" Also, when I run your program for problem #2, I get a ratio greater than 1. I'm not sure where the error is, but the ratio is always supposed to be less than 1. 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
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.
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)
# 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)
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. 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])
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) 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)
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()
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
No comments. Sign up or log in to comment 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
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
Comments:in retrospect, my solution to this problem was way more complicated than it needed to be. 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
No comments. Sign up or log in to comment ... #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
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. 'while (1)' will always return true - it's a way to loop infinitely or until broken by an explicit brk 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/n Comments:I really like your style with this one, however your isprime function is giving back true statements in the first part of your code for all odd numbers |
No comments. Sign up or log in to comment