The first few Project Euler problems are actually pretty trivial to brute force, but sometimes they have a smart solution. All in all, coming up with a semi-smart title for the post is usually harder than the problem itself. But I don’t want to leave anything out, so I’ll just continue on with problem #2:
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.
The Fibonacci sequence is a quite classic integer sequence, named after Leonardo of Pisa, aka Fibonacci. Apparently they’re used in the analysis of financial markets and much more, but I have never used it in the wild so far.
Besides that, because this solves so blazingly fast (even for numbers up to 1020). This is simply because the Fibonacci sequence gets quite big, quite fast. So I just solve this using a very simple bit of PowerShell code.
function Get-Fibonacci ($max)
{
$current = $previous = 1
$previous;
while($current -lt $max)
{
$current;
$current, $previous = ($current + $previous), $current
}
}
$measure = Get-Fibonacci 4000000 | where {$_ % 2 -eq 0} | measure-object -sum
Write-Host $measure.Sum
One thing I did find was that a recursive solution doesn’t really work, at least not in PowerShell. The default call depth is set to 100 recursive calls at most, which you will hit eventually. Not in this case though, but when testing for higher numbers it would fail. However, I think that while a calculating a Fibonacci sequence is a nice exercise to learn about recursion, it isn’t a good example of when to use recursion in the first place.