"Even Fibonacci numbers" ( https://projecteuler.net/problem=2 )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Also available as a Gist @ http://csharppad.com/gist/b9aed1a7b46d1c951f73e18032f0df84 | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Numerics; | |
namespace ProjectEuler | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int maxPos = 0; | |
int currentPos = 0; | |
BigInteger maxValue = 0; | |
BigInteger sum = 0; | |
// A function that checks to see if we're done yet. | |
Func<BigInteger, bool> isDone = x => x > 4000000; | |
// Keep looping until we've found a Fibonacci sequence value that is more than 4 million. | |
// The Fibonacci position/value we care about is the one -IMMEDIATELY BEFORE- the one with a value over 4 million. | |
while (true) | |
{ | |
currentPos++; | |
var valueAtPos = Fibonacci.GetValueByPosition(currentPos); | |
if (valueAtPos > 4000000) | |
break; | |
Console.WriteLine(String.Format("Position {0} = {1}", currentPos, valueAtPos)); | |
sum += valueAtPos; | |
maxValue = valueAtPos; | |
maxPos = currentPos; | |
} | |
// Find all of the Fibonacci values from 1..maxPos that have even values, then calculate their sum. | |
var evenKeyFibonacciValues = Enumerable.Range(1, maxPos).Select(x => Fibonacci.GetValueByPosition(x)).Where(x => x % 2 == 0); | |
sum = evenKeyFibonacciValues.Aggregate((currentSum, item) => currentSum + item); | |
Console.WriteLine(string.Format("Total = {0}", sum)); | |
} | |
} | |
public static class Fibonacci | |
{ | |
public static Dictionary<int, BigInteger> Sequence; | |
static Fibonacci() | |
{ | |
Sequence = new Dictionary<int, BigInteger> {{ 1, 1 }, { 2, 2 }}; | |
} | |
public static BigInteger GetValueByPosition(int position) | |
{ | |
if (position <= 0) | |
throw new NotSupportedException("Only positive integer values are supported in working with the Fibonacci sequence"); | |
// If we've previously calculated the Fibonacci term at the specified position, get it. | |
if (Sequence.ContainsKey(position)) | |
return Sequence[position]; | |
// The Fibonacci term has -NOT- yet been calculated for the position; calculate it using recursion. | |
var fibonacciTermValue = GetValueByPosition(position - 1) + GetValueByPosition(position - 2); | |
// Add the newly-calculated term to the dictionary of known terms. | |
Sequence.Add(position, fibonacciTermValue); | |
// Return the new value as output. | |
return fibonacciTermValue; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment