How to find the sum of all the primes below 10 (ten) 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 = 10, sum = 0;
      
        for (int i = 2; i < num; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
                sum += i;
            }
        }
          
        System.out.println("\nsum = " + sum);
    }
}
 
 
 
 
/*
run:
    
2 3 5 7 
sum = 17
    
*/

 



answered Oct 27, 2023 by avibootz
...