Skip to content

Instantly share code, notes, and snippets.

@gavinsykes
Created January 5, 2019 22:35
Show Gist options
  • Save gavinsykes/10f87b2c5f819682bfddbac73081ab51 to your computer and use it in GitHub Desktop.
Save gavinsykes/10f87b2c5f819682bfddbac73081ab51 to your computer and use it in GitHub Desktop.
<?php
/*
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.
O,E,O,O,E,O,O,E,O,O,
A number in the Fibonacci sequence can only be even if its 2 preceding terms are either both even or both odd, as it turns out, every 3rd term is even.
As it also turns out, there isn't really a whole lot I can do with this information.
*/
function euler_2($n) {
$result = 0;
$i = 1;
while (fibonacci($i) < $n) {
$i++;
if (!(fibonacci($i) & 1)) {
$result += fibonacci($i);
}
}
return $result;
}
echo euler_2(4000000); // Returns 4613732
// Function to work out the fibonacci numbers. Done as an array because it is much much faster than using a recursive function.
function fibonacci($n) {
if (!is_int($n) || $n < 1) {
return undefined; // Didn't really need this as I'm controlling the input, but you just never know.
}
if ($n == 1 || $n == 2) {
return $n;
}
$result = [1,2];
for ($i = 2;$i < $n;$i++) {
$result[$i] = $result[$i-1] + $result[$i-2];
}
return $result[$n-1];
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment