Created
June 2, 2019 16:55
-
-
Save p7g/5792b521a0432b67445371c3b2bf0006 to your computer and use it in GitHub Desktop.
Fibonacci up to 30 with C++ templates
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 Fib { | |
enum { | |
value = Fib<N - 2>::value + Fib<N - 1>::value, | |
}; | |
}; | |
template <> | |
struct Fib<1> { | |
enum { | |
value = 1, | |
}; | |
}; | |
template <> | |
struct Fib<0> { | |
enum { | |
value = 0, | |
}; | |
}; | |
template <int N> | |
static inline int fibn(int n) | |
{ | |
if (n == N) | |
return Fib<N>::value; | |
return fibn<N - 1>(n); | |
} | |
template <> | |
int fibn<-1>(int n) | |
{ | |
return -1; | |
} | |
class Solution { | |
public: | |
int fib(int N) { | |
return fibn<30>(N); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment