原题地址:http://projecteuler.net/problem=10
Summation of primes
Problem 10
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.
找出两百万以下所有质数的和。
解法1:
从2开始递增到2000000,判断每个数是否是质数,如果是则累加起来。这种解法运行起来较慢。
php代码如下所示:
function is_prime($number){
$is_prime = TRUE;
$sqrt = sqrt($number);
$root = floor($sqrt);
for($i=2;$i<=$root;$i++){
if($number%$i==0){
$is_prime = FALSE;
break;
}
}
return $is_prime;
}
$up = 2000000;
$numbers = array();
for($i=2;$i<=$up;$i++){
if(is_prime($i)){
$numbers[] = $i;
}
}
var_dump(array_sum($numbers));
注:题目的中文翻译源自http://pe.spiritzhang.com