简体   繁体   English

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

[英]Unable to find the mistake in prime number code in python

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

I am trying to find first n prime numbers but somehow this code doesn't seem to compile. 我试图找到前n个素数但不知何故这个代码似乎没有编译。 the program is getting stuck at the for loop . 该程序陷入了for循环 I have tried using writing the code in C using the same logic it seem to work fine but as i need large number support python seem to be an obvious choice and thus wanted to run in python. 我尝试使用相同的逻辑在C语言中编写代码,但效果似乎不错,但是由于我需要大量支持,因此python似乎是显而易见的选择,因此希望在python中运行。 Any help would be great. 任何帮助都会很棒。

range(a, b) goes from a to b-1 . 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

I'm betting you had 我打赌你有

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

So that by the end of the loop for a prime number, j would be i . 因此,在质数循环结束时, j将为i

Python doesn't overshoot the limit when using range . 使用range时,Python不会超出限制。

This is a good use for the otherwise-obscure syntax of else: keyword following a loop. 这对于循环之后的else:关键字的其他模糊语法很有用。 As others have commented, your test for successful completion of the for loop is off by one. 正如其他人所评论的那样,成功完成for循环的测试结果是一个。

Instead, try using else to test for successful completion: 相反,尝试使用else来测试是否成功完成:

for j in range (2,i):
        if(i%j == 0):
            break
else:
    print i
    count = count +1

Your issue is here: 你的问题在这里:

for j in range (2,i):

This checks j=2,3,4....i-1. 这检查j = 2,3,4 .... i-1。 Thus your code here is never run: 因此,您的代码永远不会运行:

if(j==i):
        print i
        count = count +1

So count never changes. 因此计数永远不会改变。 Thus you get an infinite while loop. 因此,您将获得一个无限的while循环。 Change your check to 将支票更改为

if(j==i-1):
        print i
        count = count +1

In Python 3, it's print() , not print . 在Python 3中,它是print() ,而不是print The code compiles when you change this line: 更改此行时代码将编译:

        print(i)

You also seem to have an infinite loop, but I'll let you debug that. 你似乎也有一个无限循环,但我会让你调试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM