Created
November 15, 2015 08:35
-
-
Save hamsham/55bd73f3eb4a024e6c5a to your computer and use it in GitHub Desktop.
Comparison of factorials using compile-time calculation vs runtime calculation.
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> | |
// g++ -std=c++11 -pedantic -Wall -Werror -Wextra factorial.cpp -o factorial | |
template <typename type> | |
constexpr type constFactorial( type n ) { | |
return (n > 1) ? n * constFactorial( n - 1 ) : n; | |
} | |
template <typename type> | |
inline type calcFactorial( type n ) { | |
type r = ( n ) ? 1 : n = 0; | |
while ( n ) | |
r *= n--; | |
return r; | |
} | |
int main() { | |
std::cout << "The factorial of " << 0 << " is " << constFactorial( 0 ) << std::endl; | |
std::cout << "The factorial of " << 1 << " is " << constFactorial( 1 ) << std::endl; | |
std::cout << "The factorial of " << 2 << " is " << constFactorial( 2 ) << std::endl; | |
std::cout << "The factorial of " << 3 << " is " << constFactorial( 3 ) << std::endl; | |
std::cout << "The factorial of " << 4 << " is " << constFactorial( 4 ) << std::endl; | |
std::cout << "The factorial of " << 5 << " is " << constFactorial( 5 ) << std::endl; | |
std::cout << "The factorial of " << 10 << " is " << constFactorial( 10 ) << std::endl; | |
unsigned long long i = 0; | |
unsigned long long f = 0; | |
unsigned long long err = 0; | |
do { | |
i += 1; | |
err = f; | |
f = calcFactorial( i ); | |
if ( f < err ) | |
break; | |
std::cout << "The factorial of " << i << " is " << f << std::endl; | |
} while ( f ); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment