Skip to content

Instantly share code, notes, and snippets.

@opavlyshak
Created April 26, 2013 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opavlyshak/5467592 to your computer and use it in GitHub Desktop.
Save opavlyshak/5467592 to your computer and use it in GitHub Desktop.
Using C++ templates to compute Fibonacci numbers at compile time
#include <iostream>
template <int n> struct Fib
{
enum { val = Fib<n - 1>::val + Fib<n - 2>::val };
};
template<> struct Fib<0> { enum { val = 0 }; };
template<> struct Fib<1> { enum { val = 1 }; };
int main()
{
std::cout << Fib<0>::val << std::endl;
std::cout << Fib<1>::val << std::endl;
std::cout << Fib<2>::val << std::endl;
std::cout << Fib<3>::val << std::endl;
std::cout << Fib<4>::val << std::endl;
std::cout << Fib<5>::val << std::endl;
std::cout << Fib<6>::val << std::endl;
getchar();
return 0;
}
@lnxdx
Copy link

lnxdx commented Dec 22, 2023

Using

template <unsigned long long n>
struct fib {
    enum : unsigned long long { result = fib<n - 1>::result + fib<n - 2>::result };
};
template<> struct fib<0> { enum { result = 0 }; };
template<> struct fib<1> { enum { result = 1 }; };

OR

template <unsigned long long n>
struct fib {
    static constexpr unsigned long long result = fib<n - 1>::result + fib<n - 2>::result;
};
template<> struct fib<0> { static constexpr int result = 0; };
template<> struct fib<1> { static constexpr int result = 1; };

you an compute up-to fib<105>::result which is 17704020980446223138.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment