Thursday, 24 November 2022

Java Program to find sum of n prime numbers

 

package sumofprimeno;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.logging.Level;

import java.util.logging.Logger;

  

public class Sumofprimeno {

 

       public static void main(String[] args) {

              try {

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

           

            System.out.println("Enter the value of n");

            int n = Integer.parseInt(br.readLine());

           

            int j,m=0,flag=0,sum=0;

           

             System.out.println("Enter any "+ n +" nos to check its prime or not");

             for(int i=1;i<=n;i++)

             {

             int a= Integer.parseInt(br.readLine());

             m=a/2;

             if(a==0||a==1){ 

               System.out.println(a+" is not prime number");     

             }else{ 

             for(j=2;j<=m;j++){     

             if(a%j==0){     

             System.out.println(a+" is not prime number");     

             flag=1;     

             break;     

             }     

        }     

             if(flag==0)  {

                 System.out.println(a+" is prime number");

                 sum=sum+a;

             } 

             }//end of else 

             }

             System.out.println("Sum of Prime Numbers=  "+sum);

        } catch (IOException ex) {

            Logger.getLogger(Sumofprimeno.class.getName()).log(Level.SEVERE, null, ex);

        }

        

    }

   

}

OUTPUT 1:










OUTPUT 2:










No comments:

Post a Comment