python - 如何找到对数值的总和
问题描述
我刚开始学习 Python 3,我有以下问题需要解决:
“编写一个程序,计算从 1 到某个数 n 的所有素数的对数之和,并打印出素数的对数之和。
一个。输入:整数 n
湾。输出:log(1),log(2),log(3),...,log(n) 之和(log 的底数为 10)"
解决方案
模块中有一个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
推荐阅读
- javascript - 动态创建 React Navigation 版本 3 导航器
- sql - 按月平均天数的空结果
- r - 当一个时间戳在另一个日期时间间隔之间时合并数据帧
- c# - System.ObjectDisposedException - 在使用块中使用 SQL 连接
- sql - 在 PostgreSQL 中删除与下一行具有不同值的行
- android - 在某些情况下(单例)可以在 Android 上从 Globalscope 启动协程吗?
- javascript - 如何将 CSV 图形转换为 HTML?
- css - 悬停填充按钮背景从下到上,文本颜色从下到上
- vb.net - VB.Net signedXml“Base-64 字符串中的无效字符”
- matlab - 如何对 cfit 的结果求平方?