Project Euler - Problem 10
Posted on Tue, 20/12/2011 - 15:26
Question
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Solution
$sum = 2;
for ($i = 2; $i < 2000000; $i++) {
if ($i % 2 != 1) {
continue;
}
$d = 3;
$x = sqrt($i);
while (($i % $d != 0) && $d < $x) {
$d += 2;
}
if ((($i % $d == 0 && $i != $d) * 1) == 0) {
$sum += $i;
}
}
echo $sum;Time taken to execute: 30.5757 second.
Project Euler - Problem 2
Posted on Wed, 14/12/2011 - 10:44
Question
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Solution
$prev = 2;
$prev2 = 1;
$sum = 2;
$_num = 0;
while ($_num < 4000000) {
$_num = $prev + $prev2;
$prev2 = $prev;
$prev = $_num;