DEV Community

Discussion on: Challenge: Write the recursive Fibonacci algorithm in a different language.

Collapse
 
dwd profile image
Dave Cridland
#include <iostream>

template<long long i> long long fibonacci() {
    return fibonacci<i-1>() + fibonacci<i-2>();
}

template<> long long fibonacci<1>() {
    return 1;
}

template<> long long fibonacci<2>() {
    return 1;
}

int main() {
    std::cout << "Fibonacci of 27 is " << fibonacci<27>() << std::endl;
    return 0;
}

C++ can, of course, do it at build time with a bit of templates.

Here, we're definitely recursing - twice, because it's simpler. At runtime, it's just printing the value out that's been calculated by the compiler during the build.