Wednesday, April 16, 2014

Prime numbers addition

In math, a prime number is a number only divisible by 1 and itself. Given the first few prime numbers 2 3 5 7 11 13 17 ...
What is the sum of the first 250 prime numbers


package primenumbersum;

public class Primenumbersum {

    
    public static void main(String[] args) {
        Integer val;
        Integer sum=0;
        Integer prnum=2;
        int cycle=1;
        while(cycle<251){
           if(isPrime(prnum)){
                sum+=prnum;
                   cycle++;
            }
         
           
           prnum++;
            
        }
        System.out.println("Sum: "+(int)sum);
    }
    
    //Determine whether a number is prime by doing a check

    public static boolean isPrime(int num){
       
         for(int i=2; i<num;i++){
           if (num%i==0||num==1){
               return false;
                    }
                }
      return true;
         }
}

No comments:

Post a Comment