Skip to content

Instantly share code, notes, and snippets.

@p7g
Created June 2, 2019 16:55
Show Gist options
  • Save p7g/5792b521a0432b67445371c3b2bf0006 to your computer and use it in GitHub Desktop.
Save p7g/5792b521a0432b67445371c3b2bf0006 to your computer and use it in GitHub Desktop.
Fibonacci up to 30 with C++ templates
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