python - 无法在python中找到质数代码中的错误

标签 python python-3.x primes

n=5;count=2;i=3;j=2;
while (count <= n):
    for j in range (2,i):
            if(i%j == 0):           
                break
    if(j==i):
        print i
        count = count +1
    i = i+1

我试图找到前 n 个质数,但不知何故这段代码似乎无法编译。 程序卡在 for 循环。 我曾尝试使用相同的逻辑在 C 中编写代码,它似乎工作正常,但由于我需要大量支持,python 似乎是一个明显的选择,因此想在 python 中运行。 任何帮助都会很棒。

最佳答案

range(a, b)ab-1

n=5;count=2;i=3;j=2;
while (count <= n):
    for j in range (2,i):
        if(i%j == 0):           
            break
    if(j==i-1):
        print i
        count = count +1
    i = i+1

我打赌你有

 int j;
 for(j = 2; j < i; j++) {
 }

因此到质数循环结束时,j 将是 i

Python 在使用 range 时不会超过限制。

关于python - 无法在python中找到质数代码中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19982323/

相关文章:

dictionary - 你如何遍历两个字典并在同一路径上获取值?

Python - 创建层次结构文件(在表示为表的树中查找从根到叶的路径)

python - 函数默认仅返回第一个输出值

python - 在 CentOS7 上从源代码编译 Python3.4 时无法构建可选模块 readline 和 _curses

java - 找到前n个素数并将它们存储在数组中

python - 如何将数据从 pandas 数据帧分块加载到 spark 数据帧

python - 如何组合/集成存储在 3 个数据帧中的 3 个机器学习模型的结果并输出 1 个数据帧,其结果得到多数人同意?

django - 从 Django 模板语言生成动态 HTML 表格

java - 将文件中的整数存储到数组中并查找素数 JAVA

Haskell 素数测试