How to find the sum of all the primes below 10000 (ten thousand) in Java

1 Answer

0 votes
public class MyClass {
    static boolean isPrime(int n) {
        if (n < 2 || (n % 2 == 0 && n != 2)) {
            return false;
        }
        
        int count = (int)Math.floor(Math.sqrt(n));
        for (int i = 3; i <= count; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        
        return true;
    }
     
    public static void main(String args[]) {
        int num = 10000, sum = 0;
      
        for (int i = 2; i < num; i++) {
            if (isPrime(i)) {
                sum += i;
            }
        }
          
        System.out.println("sum = " + sum);
    }
}
 
 
 
 
/*
run:
    
sum = 5736396
    
*/

 



answered Oct 27, 2023 by avibootz
...