Wednesday, 12 August 2015

Sum of Prime Number

package com.JavaInterview.Programs;

import java.util.*;

/**
 * Find Out Factorial of a number
 * 
 * @author:http://javainterviewprograms.blogspot.in/
 * 
 */

public class SumOfPrime {

 public boolean isPrime(int number) {
  boolean status = true;
  for (int i = 2; i <= number / 2; i++) {
   if (number / i == 0) {
    status = false;
    break;
   }
  }
  return status;
 }

 public void sum(int totalCount)
 {
  int number=2;
  int sum=0;
  int count=0;
  while(count <   totalCount)
  {
   if(isPrime(number))
   {
    sum+=number;
    count++;
   }
   number++;
  }
 
  System.out.println("Sum of first "+totalCount +" Prime Number is :"+sum);
 }

 public static void main(String args[])
 {
  SumOfPrime SP=new SumOfPrime();
  Scanner input=new Scanner(System.in);
 
  System.out.println("Please enter lengthof Prime number that you want to add :");
  int count=input.nextInt();
  SP.sum(count);
 }


}

Output :
Please enter lengthof Prime number that you want to add :
12

Sum of first 12 Prime Number is :90


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...