Created
May 9, 2015 14:42
-
-
Save toch/7ed3a1786d0ed464fd94 to your computer and use it in GitHub Desktop.
fibonacci template C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
Does this have an equivalent in Go after the introduction of generics?