[英]Python - Why doesn't this prime number checking algorithm work?
I have this python code that I wrote: 我有我编写的以下python代码:
from math import *
limit = 100000
primes = [2]
for i in range(3, limit+1, 2):
is_prime = True
for j in range(3, floor(sqrt(i)), 2):
if i % j == 0:
is_prime = False
break
if is_prime: primes.append(i)
print(len(primes))
It says there are 9676 primes less than 100 000, when it should be 9592. It gives the correct answer if I the replace floor(sqrt(i))
with just i
, but then it's terribly slow. 它说有9676个质数小于100000,应为9592。如果我仅用
i
替换floor(sqrt(i))
,则给出正确的答案,但是速度非常慢。 Why doesn't my algorithm work? 为什么我的算法不起作用?
Take, for example i == 9
. 以
i == 9
为例。 The following range: 范围如下:
for j in range(3, floor(sqrt(i)), 2):
Evaluates to: 评估为:
for j in range(3, 3, 2):
...which is an empty list, preventing non-prime 9 from being ruled out. ...这是一个空列表,可防止排除非素数9。 You need to go one higher to ensure that the root of square numbers is considered:
您需要提高一点以确保考虑平方根:
for j in range(3, floor(sqrt(i)) + 1, 2):
You're including primes that are squares of other primes - I changed the sqrt range definition in your code to get: 您包含的质数与其他质数的平方-我将代码中的sqrt范围定义更改为:
from math import *
limit = 100000
primes = [2]
for i in range(3, limit+1, 2):
is_prime = True
for j in range(3, floor(sqrt(i))+1, 2):
if i % j == 0:
is_prime = False
break
if is_prime: primes.append(i)
print(len(primes))
resulting in 9592 primes found 导致发现9592个素数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.