我一直在学习Python 2.5.4,我有以下问题需要解决:
“编写一个程序,计算从2到某个数n的所有素数的对数之和,并打印出素数的对数,数n和这两个量的比率之和。这适用于n的不同值。“
这是我到目前为止所做的:
from math import *
n = raw_input('This is a logarithm ratio tester. Which number do you want to test? ')
for x in range(2,n): #picks numbers to test
for divisor in range(2, 1+int(sqrt(x+1))):
if x%divisor == 0: #checks if x is prime
log(x) #computes log of prime
不幸的是,我不确定如何实现一个函数来汇总所有日志。我想,一旦我有了这个,我只需要用以下方式结束该程序:
print 'Sum of the logs of the primes is',logsum
print 'n =',n
print 'Ratio of sum to n is',logsum/n
或某些变体。但是什么是获得我标记为logsum的好方法?请注意我已经学习了不超过一周的编程,我很少知道声明/功能,我不是数学家。如果有疑问,假设我是个白痴。谢谢!
答案 0 :(得分:4)
我会将一些代码包装在函数中,并修复prime的定义:
def isprime(x):
for j in range(2,1 + int(sqrt(x - 1))):
if x%j == 0:
return False
return True
def primes(n):
return [j for j in range(2, n) if isprime(n)]
logsum = 0
for p in primes(n):
logsum += log(p)
答案 1 :(得分:3)
在计算日志之前,您应该检查数字是否为素数,然后将log(x)的值添加到变量logsum中,如下所示:
from math import *
logsum = 0
n = raw_input('This is a logarithm ratio tester. Which number do you want to test? ')
for x in range(2,n): #picks numbers to test
isprime = True
for divisor in range(2, 1+int(sqrt(x+1))):
if x%divisor == 0: #checks if x is prime
isprime = False #computes log of prime
break
if isprime:
logsum += log(x)
此外,由于您正在检查大量值,因此实施The Sieve of Eratosthenes可能是继续学习的好方法。
编辑:使用Juri Robl的建议,代码可以简化为:
from math import *
logsum = 0
n = raw_input('This is a logarithm ratio tester. Which number do you want to test? ')
for x in range(2,n): #picks numbers to test
for divisor in range(2, 1+int(sqrt(x+1))):
if x%divisor == 0: #checks if x is prime
break
else:
logsum += log(x)
答案 2 :(得分:1)
请注意log(2)+ log(3)+ ... + log(n)= log(2 * 3 * ... * n)
然后你可以使用Eratosthenes的Sieve来获得素数列表,将它们相乘,然后取该产品的对数。
import math
import operator
def filter_primes(alist, newlist):
for x in alist[1:]:
if x%alist[0] != 0:
newlist.append(x)
return newlist
n = int(raw_input('This is a logarithm ratio tester. Which number do you want to test?'))
alist = range(2, n)
sieve_list = []
primes = [2]
while alist[0] < math.sqrt(n):
a = filter_primes(alist, sieve_list)
primes.append(a[0])
alist = sieve_list
sieve_list = []
for j in alist[1:]: primes.append(j)
product = reduce(lambda x, y: x*y, primes)
ans = math.log(product)
print 'The sum of the logs is: %d \nn is: %d \nThe ratio of these two quantities is: %s' % (ans, n, float(ans/n))