Q:

Write a Java program to compute the sum of the first 100 prime numbers

0

Write a Java program to compute the sum of the first 100 prime numbers


Sample Output:

Sum of the first 100 prime numbers: 24133

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

import java.util.*;
 public class Exercise66 {
 public static void main(String[] args)
 {
    int sum = 1;
	 int ctr = 0; 
	 int n = 0; 
    	
		while (ctr < 100) {
			n++; 
			if (n % 2 != 0) { 
			// check if the number is even
				if (is_Prime(n)) {
					sum += n; 					
				}
			}
                    ctr++; 	
		}
		System.out.println("\nSum of the prime numbers till 100: "+sum); 	
	 }
	
   	public static boolean is_Prime(int n) {
		for (int i = 3; i * i <= n; i+= 2) {
			if (n % i == 0) {
				return false; 
			}
		}
		return true;
	}
}

Sample Output:

Sum of the prime numbers till 100: 1060

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now