Created
November 24, 2017 16:09
-
-
Save ArtyomLazyan/d9b45a95ceb35a213e9db8abf2124486 to your computer and use it in GitHub Desktop.
Fibonachi and Factorial
This file contains 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
#include <iostream> | |
/* Factorial template implementation */ | |
template <size_t N> struct fact; | |
template <> struct fact<0> | |
{ | |
const static size_t value = 1; | |
}; | |
template <size_t N> struct fact | |
{ | |
const static size_t value = N * fact<N - 1>::value; | |
}; | |
/* Fibonachi template implementation */ | |
template <size_t n> struct fib; | |
template <> struct fib<1> | |
{ | |
const static size_t value = 1; | |
}; | |
template <> struct fib<0> | |
{ | |
const static size_t value = 0; | |
}; | |
template <size_t n> struct fib | |
{ | |
const static size_t value = fib<n - 1>::value + fib<n - 2>::value; | |
}; | |
/* Fctrorial */ | |
size_t factorial(size_t n) | |
{ | |
if (n == 0) | |
return 1; | |
return n * factorial(n - 1); | |
} | |
/* Fibonachi */ | |
size_t fibonachi(size_t n) | |
{ | |
if (n <= 0) | |
return 0; | |
else if (n == 1) | |
return 1; | |
return fibonachi(n - 1) + fibonachi(n - 2); | |
} | |
int main() | |
{ | |
std::cout << factorial(5) << std::endl; | |
std::cout << fact<5>::value << std::endl; | |
std::cout << fibonachi(5) << std::endl; | |
std::cout << fib<5>::value << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment