el código de Python no se está ejecutando correctamente, lo mismo en Java lo hace

I was trying to solve Project Euler problem 10 using python, but my program gave a wrong result. Since I am a complete noob to python and I could not find any fault in my (apparently brute-force) logic, I wrote a program in java (almost translated it), and it gave a different result, which turned out to be right.

Aquí está el código de 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...')

The equivalent java code is:

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;
    }
}

}

I think I am doing some silly mistake or missing some subtle point.

p.s. I know my isPrime implementation is not too good. I am not printing the outputs because it may spoil the problem for others.

Any comments about (bad) style in the python program are welcome.

preguntado el 09 de marzo de 12 a las 13:03

Some comments about the Python code: 1) Don't use 1 or 0 as makeshift bool values, use True and False instead. 2) Relatedly, use checks in the form of if func() en lugar de if func() == 1). 3) Use a l = [2, 3, 5, 7 ...] y entonces if number not in l for checking for known values in a simpler way. That also gives you the benefit you can add other known primes to the list dinamically should the need arise, making some algorithms that may use isPrime (there are a lot of these in Euler) faster. -

Can you please write what was the output you were looking for and what result you got? -

@Jack_of_All_Trades The output should have been 142913828922, but the python output is 143042032103 -

3 Respuestas

Try running with your code for example isPrime(49). You should figure out your problem from there. You have replaced a > con un >= in if (tag > rootOfNumber) .Also as some coding style, you could just replace the first lines with:

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

respondido 09 mar '12, 14:03

+1: (As told by you) turns out I was not considering perfect squares, and encima de eso He utilizado > in the java version and >= in python version. My bad. - K. K.

After a quick skim it appears to me that this line in the Python version is superfluous and it might be the cause of the problem:

elif number % 2 == 0: return 0

respondido 09 mar '12, 13:03

I commented the line and ran the program, but the output is same. I don't think this line is changing anything in the wrong way. - K. K.

Why don't you return False for return value of 0? That would make it more simple.

respondido 09 mar '12, 13:03

+1: I will from now on. Right now, I was more focused on solo getting the right result. - K. K.

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.