So, I'm beggining to learn programming and trying project euler with java. The problem 10 seems pretty straight forward and I thought I could use a method I used to get primes before in another problem. The thing is, the method works except when I put it in the for loop and I can't manage to see the diference between this and the other.
So this is my code
package euler10;
public class Primesum {
public static void main(String[] args) {
int suma=0;
for (int i=0; i<2000000; i=i+2){
if (isPrime(i) == true){
System.out.println(i);
suma=suma+i;
}
}
System.out.println(suma);
}
public static boolean isPrime(int num) {
boolean prime = false;
long i;
for (i=2; i < Math.sqrt(num) ; i++){
long n = num%i;
if (n == 0){
prime = false;
} else {
prime = true;
}
}
return prime;
}
}
The isPrime method works fine out of the loop but in it it's always true. Even with even numbers it will return true, and I think those aren't very primey :)
I don't really think that there is anything to do with the loop...
However, there is a logic flaw in the code...
public static boolean isPrime(int num) {
long i;
for (i=2; i <= Math.sqrt(num) ; i++){
long n = num%i;
if (n == 0){
return false;//found a divisor : not prime
}
}
//went through all the way to sqrt(num), and found no divisor: prime!
return true;
}
We can stop whenever the first divisor is found, there is no need to find all of them -- that is another excercise...
Also, logically, if one wanted to use the boolean variable this way, it would have been initialised with true
, and put to false
, and kept at that, when a divisor is found...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments