简体   繁体   English

关于Python中Project Euler问题7的问题

[英]Question about Project Euler problem 7 in Python

I've been figuring about question 7 of project Euler.我一直在思考欧拉计划的问题 7。 I've worked out the my Python code, but it has no output, and I don't know if there are any grammatical and logical problems.我的Python代码已经算出来了,但是没有输出,不知道是不是语法和逻辑上的问题。 Would you please help me check what's wrong with it?你能帮我检查一下它有什么问题吗? Here is the original question:这是原始问题:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number?通过列出前六个质数:2、3、5、7、11、13,我们可以看出第6个质数是13。第10001个质数是多少?

def isprime(n):
    for i in range(2,n):
        if n % i == 0:
            return False
    return True
x = 3
counter = 2
while counter <= 10001:
    if isprime(x):
        counter += 1
        x += 2
    else:
        x += 2
print (x)

Your logic works fine after the following fixes:在以下修复后,您的逻辑工作正常:

  1. Correct indentation.正确的缩进。
  2. Subtract 2 from your end result.从最终结果中减去 2。

Note your implementation is inefficient.请注意,您的实施效率低下。 However, it does work.但是,它确实有效。

def isprime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

x = 3

counter = 2

while counter <= 10001:
    if isprime(x):
        counter += 1
        x += 2
    else:
        x += 2

print(x-2)  # 104743

No need to check the divisibility up to the number, just check till to the square root of the number.无需检查数字的整除性,只需检查数字的平方根即可。

import math

def is_prime(num):
    if (num < 2):
        return False
    elif (num == 2):
        return True
    else:
        divisible = False
        for i in range(2, int(math.sqrt(num)+1)):
            if (num%i == 0):
                divisible = True
        return not(divisible)
    
count = 2
number = 3

while count != 10001:
    number += 2
    if is_prime(number):
        count += 1

print(number)

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

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