Created
August 18, 2020 01:01
-
-
Save komasaru/9210636f6640c010cfacdc0d51197e44 to your computer and use it in GitHub Desktop.
C++ source code to calculate factorials with GMP.
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
/*************************************************************** | |
Factorial of N | |
by GMP(The GNU Multi Presicion Arithmetic Library). | |
$ g++ -std=c++17 -Wall -O2 --pedantic-errors -lgmp -lgmpxx -o factorial factorial.cpp | |
DATE AUTHOR VERSION | |
2020.08.17 mk-mode.com 1.00 新規作成 | |
Copyright(C) 2020 mk-mode.com All Rights Reserved. | |
***************************************************************/ | |
#include <iostream> // for cout | |
#include <gmp.h> | |
#include <gmpxx.h> | |
class Factorial { | |
public: | |
mpz_class fact(mpz_class); | |
}; | |
/* | |
* Caculation of fatorial | |
*/ | |
mpz_class Factorial::fact(mpz_class n) { | |
try { | |
if (n == 0) | |
return 1; | |
return n * fact(n-1); | |
} catch (...) { | |
throw; | |
} | |
} | |
int main(int argc, char* argv[]) { | |
Factorial f; | |
mpz_class n; | |
std::string buf; | |
try { | |
while (true) { | |
std::cout << "n? "; | |
getline(std::cin, buf); | |
if (buf.empty()) | |
break; | |
n.set_str(buf, 10); | |
std::cout << n << "! = " | |
<< f.fact(n).get_str() << std::endl; | |
std::cout << "---" << std::endl; | |
} | |
} catch (...) { | |
std::cerr << "EXCEPTION!" << std::endl; | |
return EXIT_FAILURE; | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment