python - Python - 我提取素数的查询不起作用
问题描述
我正在参加关于 Udemy 的课程,其中一个练习是从一系列数字中返回所有素数(例如 100 之前的所有素数)
这是老师提出的疑问
def count_primes2(num):
#Check for 1 or 0
if num < 2:
return 0
######################
#2 or greater
#Store our prime numbers
primes = [2] #I start my list with 2 that is a prime number
#Counter going up to the input num
x = 3 #I create a variable on which I will continue adding until I reach num
# x is going through every number up to the input num
while x <= num:
#Check if x is prime
for y in range(3,x,2): # for y in range from 3 to x in even steps, we only wantto check odd numbers there
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
count_primes2(100)
但是,我想出了下面那个不起作用的。我的想法是:
给定介于 3 和 num+1 之间的每个数字 i(例如 100 将是 101,因此 100 可以包含在计算中):
- 打开一个for 循环,在其中我将 i 除以 i 之前的每个数字 g(包括 i),并且我有一个计数器检查该除法何时没有余数。这意味着在素数的情况下,计数器应始终为 2(例如 3--> 3:1 和 3:3 将给出余数 0)。
- 如果计数器等于 2,那么 i 是素数,我想将它附加到列表中。
我没有在查询中使用任何 while 循环。您能帮我确定为什么我的查询不起作用吗?
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
return list_prime
count_prime(100)
解决方案
感谢 Khelwood的帮助。在工作查询下方:
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
counter=0
return list_prime
count_prime(100)
推荐阅读
- javascript - addEventListener 指向作为对象属性的函数,加载时不触发函数
- sonarqube - 来自 create-react-app 测试的 SonarCloud 覆盖率报告
- python - 沿同一索引合并列
- javascript - 播放后如何在leafletJS中隐藏视频覆盖?
- error-handling - 如何使错误链错误与失败错误兼容?
- python-3.x - 子数组中总和最大的所有元素,其中元素取自给定数组,使得没有两个元素相邻?
- javascript - 尝试将 jQuery 鼠标悬停转换为页面加载
- python - 试图通过嵌套的字典来理解搜索
- swift - 如何在 swift 中轻松复制不可变结构,仅更改某些字段 [如 kotlin 数据类复制方法]?
- python - 404 错误 - Twilio Python 快速入门