Q)The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Solution:
Again use any Sieve (atkins or eratosthenes) for faster solution. Brute force(which this solution has used) is very slow for this one.
Java code:
public class Prob10 {
public static void main(String[] args) {
long sum = 2;
for (int i = 3 ; i < 2000000; i = i+2)
{
if (checkPrime(i))
{
sum += i;
System.out.println(i);
}
}
System.out.println(sum);
}
public static boolean checkPrime(int a)
{
boolean flag = true;
for(int i = 3 ; i < a ; i = i+2 )
{
if(a % i == 0 )
{
flag = false;
break;
}
}
return flag;
}
}
No comments:
Post a Comment