Project Euler in PHP
Project Euler is a series of challenging mathematical/computer programming problems, their website is http://www.projecteuler.net
-
Add all the natural numbers below one thousand that are multiples of 3 or 5.
PHP Code:
$y = array();
for($i=1;$i<1000;$i++){
if (!($i%3)||!($i%5)){
$y[] = $i;
}
}
echo array_sum($y);
Answer: 233,168 -
Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
PHP Code:
$total=0;
$a=1;
$b=1;
for ($c=$a+$b;$c<4000000;$c){
$total=$total+$c;
$a=$b+$c;
$b=$c+$a;
$c=$a+$b;
}
echo $total;
Answer: 4,613,732 -
Find the largest prime factor of a composite number. (600851475143 in this question)
Answer: 6,857 -
Find the largest palindrome made from the product of two 3-digit numbers.
Answer: 906,609 -
What is the smallest number divisible by each of the numbers 1 to 20?
PHP Code:
$i = 1;
$x = 1;
while ($x <= 20) {
if ($i%$x == 0) {
$x++;
} else {
$i++;
$x = 1;
}
}
echo $i;
Answer: 232,792,560 -
What is the difference between the sum of the squares and the square of the sums?
Answer: -
Find the 10001st prime.
PHP Code:
function prime($n){
if($n%2 == 0){
return 0;
}
$temp = ceil(sqrt($n)) +1;
while($temp > 1){
if($n % $temp == 0){
return 0;
}
$temp -= 1;
}
return 1;
}
$t = 7;
$count = 3;
while($count < 10001){
$bool = prime($t);
$t += 1;
if($bool == 1){
$count += 1;
}
}
print $t-1;
Answer: 104,743 -
Discover the largest product of five consecutive digits in the 1000-digit number.
Answer: -
Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.
Answer: -
Calculate the sum of all the primes below two million.
PHP Code:
$n = 2000000;
$p = 2;
$list = range($p, $n);
$i = 0;
while($p*$p < $n){
for($j=$i+1; $j < $n; $j++){
if($list[$j] % $p == 0){
unset($list[$j]);
}
}
sort ($list);
$i = $i + 1;
$p = $list[$i];
}
echo array_sum($list);
Answer: 142,913,828,922
There will be more solved here soon.
