帮助将 CF 高斯的素数假设添加到我的埃拉托色尼筛中
嘿大家! 所以我几乎已经完成了我开始为学校解决的一个涉及埃拉托色尼筛的问题。我设法让程序打印出从 2 到 1000 的平方根的所有素数。但是,我的老师要求我使用 CF 高斯的素数假设(?)。他是这么说的: CF高斯假设定义(N)小于或等于N的素数个数 当 N 接近无穷大时,(N) = N/loge(N)。这被称为素数 假设。在 for 循环中打印素数,一个指示其序数的计数器 数字(1、2、3 等)和 (N) 的值。
我尝试制作另一个 for 循环,并打印素数,但它对我不起作用! :( 呃。 任何帮助将不胜感激! :)
import math
def sieves(N):
x = 1000*[0]
prime = 2
print('2')
i = 3
while (i <= N):
if i not in x:
print(i)
prime += 1
j = i
while (j <= (N / i)):
x.append(i * j)
j += 1
i += 2
print("\n")
def main():
count = 0
for i in range (1000):
count = count + 1
print(sieves(math.sqrt(1000)))
main()
Hey all!
So I'm almost done with a problem that I started working on for school that deals with the Sieve of Eratosthenes. I managed to get the program to print out all the prime numbers from 2 to the square root of 1000. However, my teacher is asking me to use the Prime Number Hypothesis (?) by C.F. Gauss. This is what he says:
C. F. Gauss hypothesized that (N) the number of primes less than or equal to N is defined
as (N) = N/loge(N) as N approaches infinity. This was called the prime number
hypothesis. In a for loop print the prime numbers, a counter indicating its ordinal
number (1, 2, 3, etc.) and the value of (N).
I tried making another for loop, and printing the prime numbers but it's just not working for me! :( ugh.
Any help would be greatly appreciated! :)
import math
def sieves(N):
x = 1000*[0]
prime = 2
print('2')
i = 3
while (i <= N):
if i not in x:
print(i)
prime += 1
j = i
while (j <= (N / i)):
x.append(i * j)
j += 1
i += 2
print("\n")
def main():
count = 0
for i in range (1000):
count = count + 1
print(sieves(math.sqrt(1000)))
main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题似乎出在 j=i 行。您希望开始 j = 1,以便捕获 i 的所有倍数并将它们添加到非素数元素的“x”列表中。如果你开始 j = i 你会错过一些。当您测试“i not in x”时,对于某些非素数,它将评估为 true。
另外,您可能指的是 x[i*j] = 1 (即设置为 1 意味着 i*j == 非素数),而不是 x.append(i*j)
通过该修改,“i not in x”可以优化为“x[i] == 0”,无需搜索整个数组。这比保留稀疏数组“x”并且必须在循环中的每一步搜索它的元素要有效得多。
The problem seems to be in the line j=i. You want to start j = 1 so that you catch all multiples of i and add them to your "x" list of non-prime elements. If you start j = i you will miss some. And when you test for "i not in x" it will evaluate to true for some non-primes.
Also instead of x.append(i*j) you probably meant x[i*j] = 1 (i.e. set to 1 means i*j == not prime)
With that modification "i not in x" can be optimized to "x[i] == 0", no reason to search the entire array. This would be a lot more efficient than keeping a sparse array "x" and having to search it's elements every step in the loop.