Problem : 2.21


Question 2.21:  Write a Java program to compute the sum of the first 100 prime numbers.

Sample Output:
Sum of the first 100 prime numbers: 24133


Solution: 


package com.company;
import java.util.Scanner;
public class lab2problem21 {
    public static void main(String[] args) {
        Scanner Obj = new Scanner(System.in);
        int n = Obj.nextInt();
        int d = 0;
        int sum=0;
        for (int i = 2; d < n; i++)
        {
            int c = 0;
            for (int j = 2; j <= i; j++) {
                if (i % j == 0) {
                    c++;
                }
            }
            if(c<2)
            {
                sum = sum + i;
                d++;

            }

        }
        System.out.println("total :" + sum);

    }
}





Previous Post Next Post