首页 > 解决方案 > 如何找到对数值的总和

问题描述

我刚开始学习 Python 3,我有以下问题需要解决:

“编写一个程序,计算从 1 到某个数 n 的所有素数的对数之和,并打印出素数的对数之和。

一个。输入:整数 n

湾。输出:log(1),log(2),log(3),...,log(n) 之和(log 的底数为 10)"

标签: pythonlogarithmnatural-logarithm

解决方案


模块中有一个log10函数math,所以你不需要自己弄清楚如何计算日志。所以你会做这样的事情:

import math

def is_prime(x):
    # Write a function that returns whether x is prime

def log_sum(n):
    # Return the sum of all logs for primes smaller than n
    log_total = 0
    for i in range(1, n+1):
        if is_prime(i):
            log_total += math.log10(i)
    return log_total

推荐阅读