4

我一直在学习 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 的好方法?请注意,我学习编程的时间不超过一周,我对语句/函数的了解很少,而且我不是数学家。如有疑问,请假设我是个白痴。谢谢!

4

3 回答 3

4

我会将您的一些代码包装在函数中,并修复您对素数的定义:

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)
于 2014-02-16T23:39:39.460 回答
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)
于 2014-02-16T23:36:14.257 回答
1

注意 log(2) + log(3) + ... + log(n) = log(2*3*...*n)

然后,您可以使用 Eratosthenes 筛获得素数列表,将它们相乘,然后取该乘积的对数。

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))
于 2014-02-17T02:25:40.493 回答