Home > front end >  Any ideas on why my program to calculate the sum of all the primes les than a certain number is brea
Any ideas on why my program to calculate the sum of all the primes les than a certain number is brea

Time:09-22

I am trying to find the sum of all the primes below 2000000, and my program works fine until I enter any number larger than 225287, after which it starts giving incorrect answers. Any ideas?

public class PrimeSum {

    
    public static void main(String[] args) {
        PrimeSum is = new PrimeSum();
        int total = 0;
        
        for(int i = 2; i < 225287; i   ){
            if(is.isPrime(i)){
                total  = i;
                System.out.println(i);
            }
        }
        System.out.println(total);
    }
    boolean isPrime(int i ){
        Boolean prime = true;
        
        for(int n = 2; n< i; n  ){
            if(i % n == 0){
                prime = false;
                break;
            }
        }
        return prime;
    }
}

CodePudding user response:

Seems, int total = 0; is not able to hold such large number.

int type which is size in 4 bytes that stores whole numbers from -2,147,483,648 to 2,147,483,647

long type which is size in 8 bytes that stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Now, see yourself which suitable for you.

CodePudding user response:

Once you reach 225287, the sum is 2147431330. The max value of int is 2147483647, so adding the next prime number leaves you out of bounds of int, which causes the the binary data to roll over to the negative side.

If you want your method to produce higher sums, you will need to change data type.

As a side note, you can optimize isPrime(int i) by only looping up to Math.sqrt(i).

  • Related