Skip to content

Instantly share code, notes, and snippets.

@toch
Created May 9, 2015 14:42
Show Gist options
  • Save toch/7ed3a1786d0ed464fd94 to your computer and use it in GitHub Desktop.
Save toch/7ed3a1786d0ed464fd94 to your computer and use it in GitHub Desktop.
fibonacci template C++
template<int n>
struct fibonacci
{
static constexpr int value = fibonacci<n-1>::value + fibonacci<n-2>::value;
};
template<>
struct fibonacci<0>
{
static constexpr int value = 0;
};
template<>
struct fibonacci<1>
{
static constexpr int value = 1;
};
int main()
{
fibonacci<40>::value;
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