Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created August 18, 2020 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/9210636f6640c010cfacdc0d51197e44 to your computer and use it in GitHub Desktop.
Save komasaru/9210636f6640c010cfacdc0d51197e44 to your computer and use it in GitHub Desktop.
C++ source code to calculate factorials with GMP.
/***************************************************************
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