python代码没有正确运行,在java中也是如此

我试图使用
python解决Project Euler问题10,但我的程序给出了错误的结果.因为我是一个完整的pyob toob,我在我的(显然是暴力)逻辑中找不到任何错误,我在
java中编写了一个程序(几乎翻译了它),它给出了一个不同的结果,结果证明是正确的.

这是python代码:

from math import *

limit = 2000000

def isPrime(number):
    if number == 2: return 1
    elif number % 2 == 0: return 0
    elif number == 3: return 1
    elif number == 5: return 1
    elif number == 7: return 1
    else:
        rootOfNumber = sqrt(number)
        tag = 3
        while tag < rootOfNumber:
            if number % tag != 0:
                tag += 2
            else:
                break           ###   
        if tag >= rootOfNumber: ###EDIT: it should by only tag > rootOfNumber here
            return 1            ###       Thats what the problem was.
        else:
            return 0

sum = 2 # 2 is an even prime, something we are not iterating for
for i in range(3, limit, 2):
    if isPrime(i) == 1:
        sum += i

print(sum)
print('done...')

等效的java代码是:

public class Prob10{
static int limit = 2000000;
static long sum = 2L; // 2 is an even prime, something we are not iterating for

public static void main (String[] args) {
    for(int i = 3; i < limit; i+=2) {
    if( isPrime(i) ) 
        sum += i;
    }
    System.out.println(sum);
}

private static boolean isPrime (int number) {
    if (number == 2) return true;
    else if (number == 3 || number == 5 || number == 7) return true;
    else {
        double rootOfNumber = Math.sqrt(number);
        int tag = 3;
        while (tag < rootOfNumber) {
            if (number % tag != 0) 
                tag +=2;
            else
                break;
        }
        if (tag > rootOfNumber)
            return true;
        else
            return false;
    }
}

}

我想我正在做一些愚蠢的错误或遗漏一些微妙的观点.

附:我知道我的isPrime实现不太好.我不打印输出,因为它可能会破坏其他人的问题.

欢迎任何有关python程序中(坏)样式的评论.

最佳答案 尝试使用代码运行,例如isPrime(49).你应该从那里找出你的问题.你已经取代了>使用> = in if(tag> rootOfNumber)

.作为一些编码风格,你可以用以下代码替换第一行:

if i in (2, 3, 5, 7): return 1
elif number % 2 == 0: return 0
else:
    ......
点赞