2

I'm trying to answer project Euler #10, which is to find the sum of primes between 1-2000000. Every time I run my code, it gives me 0, and I can't figure out why.

public static boolean isPrime (int n) 
{
    double a = Math.sqrt(n);
    for(int i = 1; i < a; i++){
        if(n % i == 0){
            return false;
        }
    }
    return true;
}

public static void main (String[] args)
{
    long sum = 0;
    for(int i = 2; i < 2000000; i++){
        if(isPrime(i)==true){
            sum+= i;
        }
    }
    System.out.println(sum);
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
boboosaget
  • 45
  • 1

5 Answers5

15

Change

for (int i = 1; i < a; i++) {

to

for (int i = 2; i < a; i++) {

Any number is divisible by 1, even prime numbers.

Based on your current code, no number is prime.

Eran
  • 387,369
  • 54
  • 702
  • 768
4

Apart from the logic in your code any integer modulo 1 is zero makes your isPrime method to break out of the loop and return false, so you should start loop from 2 instead.

 for(int i = 1; i < a; i++){
        if(n % i == 0){//for 1 loop gets break;
akash
  • 22,664
  • 11
  • 59
  • 87
2

Please check out the typo as mentioned already..

Also in isPrime method, i should start with 2 and not 1.

public static boolean isPrime(int n){
        double a = Math.sqrt(n);
        for(int i = 2; i < a; i++){
            if(n % i == 0){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args){
        long sum = 0;
        for(int j = 2; j < 2000000; j++){
            if(isPrime(j)==true){
                sum+= j;
            }
        }
        System.out.println(sum);
    }
user1401472
  • 2,203
  • 3
  • 23
  • 37
2

Your isprime logic is wrong,

if(n % i == 0)

ALWAYS returns a true statement causing it to return false. All numbers are divisible by 1.

Luigi
  • 439
  • 5
  • 23
1
public static boolean isPrime (int n) 
{   
    double a = Math.sqrt(n);
    int b =(int)Math.sqrt(n);
    if(Math.pow(b,2)==n)
    {
        return false;
    }

    for(int i = 2; i < a; i++){
        if(n % i == 0){
            return false;
        }
    }
    return true;
}

public static void main (String[] args)
{
    long sum = 0;
    for(int i = 2; i < 200000; i++){
        if(isPrime(i)==true){
            sum+= i;
        }
    }
    System.out.println("Total is " +sum);
}
StormeHawke
  • 5,987
  • 5
  • 45
  • 73
  • 1
    I fixed your code formatting for you but you'll want to be careful about that around here. Also, it's encouraged to provide a little explanation as to how your code answers the question – StormeHawke Oct 29 '14 at 18:27