Search code examples
javamoduloadditionmodular-arithmetic

What is an efficient method for adding thousands of numbers quickly?


I am attempting to solve a challenge, but I have hit a roadblock. I am a beginner programmer attempting to add tens of thousands of numbers. If I wait long enough, my program can easily yield the correct sum, however, I am looking for a more efficient method.

What is an efficient method for adding thousands of numbers quickly?

Side note: I have been reading about modular arithmetic, but I cannot quite wrap my head around it. Not sure if that could be useful for this situation.

I am attempting to get the sum of every prime number below 2 000 000. Here is my code so far:

public class Problem10 {
    public static void main (String[] args) {
        long sum = 0L;

        for(long i = 1L; i < 2000000; i++) {
            if(isPrimeNumber((int)i)) {
                sum += i;
            }
        }
        System.out.println(sum);
    }

    public static boolean isPrimeNumber(int i) {
        int factors = 0;
        int j = 1;

        while (j <= i) {
            if (i % j == 0) {
                factors++;
            }
            j++;
        }
        return (factors == 2);
    }
}

Solution

  • You can replace your isPrimeNumber() method with this to speed it up substantially.

    public static boolean isPrimeNumber(int i) {
        if (i==2) return true;
        if (i==3) return true;
        if (i%2==0) return false;
        if (i%3==0) return false;
    
        int j = 5;
        int k = 2;
    
        while (j * j <= i) {
            if (i % j == 0) return false;
            j += k ;
            k = 6 - k;
    
        }
        return true;
    }