DEV Community

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

Collapse
 
dwd profile image
Dave Cridland
#include <iostream>

constexpr long long fibonacci(long long i) {
    if (i <= 2) {
        return 1LL;
    }
    return fibonacci(i - 1) + fibonacci(i - 2);
}

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

Modern C++ can do it more simply, though - this uses constexpr to tell the compiler that it can calculate these at build time if it wants. Using a constexpr arg (here a literal), it probably will do, but we could also pass in a variable to make it calculate it at runtime.