Monday, October 13, 2014

Summation of Primes

Ques:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

Ans:
public static void main(String[] args) {
        int count = 0;
        int pcount=1;
        int tarprnum=10001;
        int sump=2;
        for (int i = 3; i < 2000000; i++) {
            count=0;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                           count++;
                    break;
                }
            }
            if(count==0){
                pcount++;
                sump+=i;
                           }
                 }
        System.out.println("sum="+sump);
    }

}

No comments:

Post a Comment