Search code examples
c++recursiondynamicdynamic-programmingfibonacci

What is wrong with my code? Nth Fibonacci Number


  public:
  
    long long int lookup[100]={-1};
    long long int nthFibonacci(long long int n){
        // code here
    
        if(lookup[n]==-1){
            if(n<=1) lookup[n]=n;
            else lookup[n]=nthFibonacci(n-1)+nthFibonacci(n-2);
        }
        return lookup[n];
    }
};

This is my code. It is giving output 0 for input 2, instead it should give 1.


Solution

  • OK, we are talking about Fibonacci numbers and memoization.

    The ultrafast and compact solution is to use compile time memoization. So, precalculate all possible values, that fit into a 64 unsigned bit, value during compile time.

    One important property of the Fibonacci series is that the values grow strongly exponential. So, all existing build in integer data types will overflow rather quick.

    With Binet's formula you can calculate that the 93rd Fibonacci number is the last that will fit in a 64bit unsigned value.

    And calculating 93 values during compilation is a really simple and fast task.

    So, how to do?

    We will first define the default approach for calculation a Fibonacci number as a constexpr function. Iterative and non recursive.

    // Constexpr function to calculate the nth Fibonacci number
    constexpr unsigned long long getFibonacciNumber(size_t index) noexcept {
        // Initialize first two even numbers 
        unsigned long long f1{ 0 }, f2{ 1 };
    
        // calculating Fibonacci value 
        while (index--) {
            // get next value of Fibonacci sequence 
            unsigned long long f3 = f2 + f1;
            // Move to next number
            f1 = f2;
            f2 = f3;
        }
        return f2;
    }
    

    With that, Fibonacci numbers can easily be calculated at compile time. Then, we fill a std::array with all Fibonacci numbers. We use also a constexpr and make it a template with a variadic parameter pack.

    We use std::integer_sequence to create a Fibonacci number for indices 0,1,2,3,4,5, ....

    That is straigtforward and not complicated:

    template <size_t... ManyIndices>
    constexpr auto generateArrayHelper(std::integer_sequence<size_t, ManyIndices...>) noexcept {
        return std::array<unsigned long long, sizeof...(ManyIndices)>{ { getFibonacciNumber(ManyIndices)... } };
    };
    

    This function will be fed with an integer sequence 0,1,2,3,4,... and return a std::array<unsigned long long, ...> with the corresponding Fibonacci numbers.

    We know that we can store maximum 93 values. And therefore we make a next function, that will call the above with the integer sequence 1,2,3,4,...,92,93, like so:

    constexpr auto generateArray() noexcept {
        return generateArrayHelper(std::make_integer_sequence<size_t, MaxIndexFor64BitValue>());
    }
    

    And now, finally,

    constexpr auto FIB = generateArray();
    

    will give us a compile-time std::array<unsigned long long, 93> with the name FIB containing all Fibonacci numbers. And if we need the i'th Fibonacci number, then we can simply write FIB[i]. There will be no calculation at runtime.

    I do not think that there is a faster or easier way to calculate the n'th Fibonacci number.

    Please see the complete program below:

    #include <iostream>
    #include <array>
    #include <utility>
    // ----------------------------------------------------------------------
    // All the following will be done during compile time
    
    // Constexpr function to calculate the nth Fibonacci number
    constexpr unsigned long long getFibonacciNumber(size_t index) {
        // Initialize first two even numbers 
        unsigned long long f1{ 0 }, f2{ 1 };
    
        // calculating Fibonacci value 
        while (index--) {
            // get next value of Fibonacci sequence 
            unsigned long long f3 = f2 + f1;
            // Move to next number
            f1 = f2;
            f2 = f3;
        }
        return f2;
    }
    // We will automatically build an array of Fibonacci numberscompile time
    // Generate a std::array with n elements 
    template <size_t... ManyIndices>
    constexpr auto generateArrayHelper(std::integer_sequence<size_t, ManyIndices...>) noexcept {
        return std::array<unsigned long long, sizeof...(ManyIndices)>{ { getFibonacciNumber(ManyIndices)... } };
    };
    
    // Max index for Fibonaccis that for in an 64bit unsigned value (Binets formula)
    constexpr size_t MaxIndexFor64BitValue = 93;
    
    // Generate the required number of elements
    constexpr auto generateArray()noexcept {
        return generateArrayHelper(std::make_integer_sequence<size_t, MaxIndexFor64BitValue>());
    }
    
    // This is an constexpr array of all Fibonacci numbers
    constexpr auto FIB = generateArray();
    // ----------------------------------------------------------------------
    
    // Test
    int main() {
    
        // Print all possible Fibonacci numbers
        for (size_t i{}; i < MaxIndexFor64BitValue; ++i)
    
            std::cout << i << "\t--> " << FIB[i] << '\n';
    
        return 0;
    }
    

    Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.

    Additionally compiled and tested with clang11.0 and gcc10.2

    Language: C++17