【发布时间】:2015-02-22 19:44:52
【问题描述】:
我正在尝试编写一个程序来计算所有小于给定数字的素数,以及所有这些素数乘积的自然对数。因此,因为我们正在使用对数,所以我也可以添加每个小于给定数字的素数的自然对数。所以我创建了这个程序,但我觉得对数有点奇怪?我尝试检查我的程序给出的总和是否正确,但首先我的程序只给出整数作为答案,其次我的计算器给出了不同的答案。我的代码有问题吗?素数工作正常,但如前所述,对数是错误的。我的代码见下文
def prime_program():
while True:
answer = raw_input("Do you want to know the primes smaller than a number n and the natural logarithm of the product of those primes? Please answer yes or no ")
if answer == "yes":
n = float(raw_input("Please enter a whole number bigger than 1 "))
counter = 1
prime = 3.0
log_of_prime_sum = float(log(2.0)) #I'm starting out with log(2.0) cause 2 is the first prime not counted later
if n > 2.0:
print "these are the primes smaller than %d" % n
print 2.0 #cause I want to see all the primes but only want to check the odd numbers
while prime < n:
for x in range(2,int(sqrt(prime))+1): #range only works with integers right?
if prime%x == 0.0:
break#because if it isn't a prime I don't want to do anything with it
else:
print(prime) #cause I want to know the primes
log_of_prime_sum += float(log(prime)) #cause I want to add all the logs of the primes
prime += 2.0 #we're starting with three, which is an odd,
#and I'm adding two because I only want to check the odd numbers,
#because no even number other than two is prime
print "the natural logarithm of the product of all the primes smaller than %d is %d" % (n, log_of_prime_sum)
ratio = float(float(n)/float((log_of_prime_sum)))
print "The ratio of %d to the sum of the natural logarithms smaller than %d is %d" % (n, n, ratio) #here I want to print the ratio of n and the log_of_prime_sum
else:
print "There is no prime smaller than 2"
elif answer == "no": #like what why would anyone open this file if he wouldn't want to do this lol
print "well ok then"
else:
print "I'm sorry that was not a valid answer, you can only answer yes or no"
continue #jumps back to while True:
return #finished; exit the function
#here I want to go back to answer = raw_input
prime_program()
这是我在 windows powershell 中的输出
Do you want to know the primes smaller than a number n and the natural log
arithm of the product of those primes? Please
answer yes or no yes
Please enter a whole number bigger than 1 8
these are the primes smaller than 8
2.0
3.0
5.0
7.0
the natural logarithm of the product of all the primes smaller than 8 is 5
The ratio of 8 to the sum of the natural logarithms smaller than 8 is 1
【问题讨论】:
-
这段代码是否正确缩进?
-
我这么认为?当我运行我的程序时,它工作正常,除了日志的总和大声笑
标签: python loops sum primes logarithm