简体   繁体   English

查找第 1000 个素数(python)调试

[英]Finding the 1000th prime number (python) debug

I am attempting to write a code to calculate the 1000th prime number and I'm running into an issue with my loop counter that i don't understand.我正在尝试编写代码来计算第 1000 个素数,但我的循环计数器遇到了我不理解的问题。

prime_test = 1
count=0
for count in range(0,1001):
    for divisor in range(2,prime_test):
        if (prime_test % divisor) == 0:
            break
    else:
        print(prime_test)
        count += 1
    prime_test+=1

Could someone please explain why the above code is dysfunctional?有人可以解释为什么上面的代码功能失调吗? The problem is that the count variable iterates at the same rate as the prime_test variable.问题是 count 变量以与 prime_test 变量相同的速率迭代。 How do I separate the two such that count only increases when a new prime is found and not when the loop is engaged?如何将两者分开,以便计数仅在找到新素数时增加,而不是在使用循环时增加?

Don't use for count in range(0, 1001): .不要使用for count in range(0, 1001): That just increments count sequentially, not when it finds a prime.这只是按顺序递增计数,而不是在找到素数时。 Use a while loop.使用while循环。

prime_test = 2
count = 0
while count < 1000:
    for divisor in range(2,prime_test):
        if (prime_test % divisor) == 0:
            break
    else:
        print(prime_test)
        count += 1
    prime_test += 1

You also should start prime_test at 2 , not 1 , since 1 isn't a prime number, but your algorithm will say it is.您还应该从2而不是1开始prime_test ,因为1不是质数,但您的算法会说它是。

One more answer as the same thing might need to be repeated thousand times before it could be understood.同一件事的另一个答案可能需要重复上千次才能被理解。

Setting the value of c before the loop has no effect at all and the new to c within the loop assigned value will be overwritten by next loop loop as c will be set to the next value provided by range() .在循环之前设置c的值根本没有任何影响,并且循环分配值内的c的新值将被下一个循环循环覆盖,因为c提供的下一个值将设置为range()的下一个值。 Python for c in range() loops are not like loops in some other programming languages. for c in range()其他一些编程语言中的循环不同。 So every newbie has to go through this... wondering how it comes.所以每个新手都必须通过这个 go...想知道它是怎么来的。

Following code demonstrates this:以下代码演示了这一点:

c = 100
for c in range(5):
    print(c, end=' -> ')
    c = c + 5
    print(c)

printing印刷

0 -> 5
1 -> 6
2 -> 7
3 -> 8
4 -> 9


If you change your code to:如果您将代码更改为:

prime_test = 2
counter=0
for count in range(0,11):
    for divisor in range(2, prime_test):
        if (prime_test % divisor) == 0:
            break
    else:
        print(prime_test)
        counter += 1
    prime_test+=1
print(f'{counter=} , {prime_test=} ')

you will get as output:你会得到 output:

2
3
5
7
11
counter=5 , prime_test=13

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

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