Skip to main content
Kevin M. Miller

Engineering · Systems · Judgment

Writing · December 1, 2021

Language Comparison Euler Problem Two

An article by Kevin M. Miller, published December 1, 2021.

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.

F#


let maxFibonacciNumber = 4000000

let FindTotal (numbers:int seq) = 
    numbers |> Seq.where (fun x -> x % 2 = 0) |> Seq.sum 

let numbers = 
    Seq.unfold
            (
                fun state -> 
                    let currentNumber, secondNumber = state
                    let nextNumber = currentNumber + secondNumber

                    match currentNumber with 
                    | x when x > maxFibonacciNumber -> None
                    | _ -> Some(nextNumber, (secondNumber, nextNumber))
             )(1,1)

FindTotal numbers

SQL


DECLARE @i INT
DECLARE @nMinusOne INT
DECLARE @nMinusTwo INT

DECLARE @total INT

SET @i = 1
SET @nMinusOne = 1
SET @nMinusTwo = 0
SET @total = 0

WHILE @i < 4000000 
BEGIN
IF @i % 2 = 0 
BEGIN
SET @total = @total + @i
END

SET @nMinusTwo = @nMinusOne
SET @nMinusOne = @i

SET @i = @nMinusOne + @nMinusTwo

END

PRINT @Total 

C#


public static void Main()
{
    var maxNumber = 4000000;
    var result = GetFibonacci(maxNumber).Where (x=>x % 2 == 0).Sum();
    Console.WriteLine(result);
}

static IEnumerable<int> GetFibonacci(int maxNumber)
{
    var previousFibonacciNumber = 0; 
    var currentFibonacciNumber = 1;

    while(currentFibonacciNumber < maxNumber)
    {
        yield return currentFibonacciNumber;

        var temp = currentFibonacciNumber + previousFibonacciNumber;
        previousFibonacciNumber = currentFibonacciNumber;
        currentFibonacciNumber  = temp;
    }

}

Continue reading

More writing