Project Euler #2 – Even Fibonacci Numbers


Problem Overview



C Solution

#include <stdio.h>
#include <stdint.h>

/// Even Fibonacci Numbers

// Fibonacci Series defined in the Problem 2:
// fib(0) = 1
// fib(1) = 2
// fib(2) = 3
// fib(3) = 5
// fib(4) = 8
// ...
// fib(n) = fib(n-1) + fib(n-2)

#define FOUR_MILLION (4000000ul)

uint64_t fib(uint64_t n)
{
    if (n == 0)
    {
        return 1;
    }

    if (n == 1)
    {
        return 2;
    }

    return fib(n-1) + fib(n-2);
}

uint64_t solve()
{
    uint64_t sum = 0;
    uint64_t n = 0;
    while (1)
    {
        uint64_t term = fib(n);
        if (term > FOUR_MILLION)
        {
            break;
        }
        if (term % 2 == 0)
        {
            sum += term;
        }
        n++;
    }
    return sum;
}

int main()
{
    printf(
        "The sum of the even-valued fibonacci numbers whose values do not exceed four million: %lu\n",
        solve());
    return 0;
}

  1. Key Ideas



  2. The fib Function

  3. uint64_t fib(uint64_t n)
    {
        if (n == 0)
        {
            return 1;
        }
    
        if (n == 1)
        {
            return 2;
        }
    
        return fib(n-1) + fib(n-2);
    }
    


  4. The solve Function

  5. uint64_t solve()
    {
        uint64_t sum = 0;
        uint64_t n = 0;
        while (1)
        {
            uint64_t term = fib(n);
            if (term > FOUR_MILLION)
            {
                break;
            }
            if (term % 2 == 0)
            {
                sum += term;
            }
            n++;
        }
        return sum;
    }
    


  6. main and Output

  7. int main()
    {
        printf(
            "The sum of the even-valued fibonacci numbers whose values do not exceed four million: %lu\n",
            solve());
        return 0;
    }
    


  8. Complexity and Possible Improvement



Common Lisp Solution

  1. Problem Setup



  2. Full Lisp Solution
  3. (defvar *four-million* 4000000)
    
    (defun sum-even-fibonacci-numbers (upper-bound-inclusive)
      (loop for a = 1 then b
            and b = 2 then (+ a b)
            while (<= a upper-bound-inclusive)
            when (evenp a) sum a))
    



  4. Understanding the loop Construct



  5. Example Evaluation
  6. * (sum-even-fibonacci-numbers *four-million*)
    4613732
    



  7. Highlights



  8. Performance