2
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 中运行。任何帮助都会很棒。

4

4 回答 4

6

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

Python doesn't overshoot the limit when using range.

于 2013-11-14T16:02:34.607 回答
1

else:这对于循环后关键字的其他晦涩语法很有用。正如其他人所评论的那样,您对成功完成for循环的测试已经过关了。

相反,尝试使用else来测试是否成功完成:

for j in range (2,i):
        if(i%j == 0):
            break
else:
    print i
    count = count +1
于 2013-11-14T16:12:06.333 回答
0

在 Python 3 中,它是print(),而不是print。当您更改此行时,代码将编译:

        print(i)

你似乎也有一个无限循环,但我会让你调试它。

于 2013-11-14T16:06:37.870 回答
0

你的问题在这里:

for j in range (2,i):

这将检查 j=2,3,4....i-1。因此,您的代码永远不会运行:

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

所以计数永远不会改变。因此你得到一个无限的while循环。将您的支票更改为

if(j==i-1):
        print i
        count = count +1
于 2013-11-14T16:04:27.783 回答