題目
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
計算兩百萬以下所有質數的和。
10以下的質數的和是2 + 3 + 5 + 7 = 17.
找出兩百萬以下所有質數的和。
解答:Java程序
public class N_10 {
public static void main(String []args){
sumPrime();
}
public static void sumPrime(){
long sum=2;
for(int i=3;i<=2000000;i=i+2)
{
boolean flag = true;
for(int j=2;j*j<=i;j++)
{
if(i%j==0)
{
flag = false;
break;
}
}
if(flag)
{
sum = sum + i;
}
}
System.out.println(sum);
}
}
運行結果:142913828922