Reputation: 1330
I wrote a code to get the factorial of a number in C++.
Here is the code.
#include <iostream>
using namespace std;
unsigned long long getFactorial(int);
int main(int argc, char **argv) {
int num = 5;
unsigned long long factorial = getFactorial(a);
cout << "Factorial of " << num << ": " << factorial << endl;
return 0;
}
unsigned long long getFactorial(int num) {
int i;
unsigned long long factorial = 1;
for(i=1; i<=num; i++) {
factorial *= i;
}
return factorial;
}
When I assign 5 to the num
value, it properly prints out the right value, 120. But when I assign bigger numbers, for example 100, it simply prints out 0. How can I modify the code to properly print out the result on the console?
Upvotes: 0
Views: 10408
Reputation: 1330
Now I found the answer by myself.
By using the gmp
library, it became much easier to deal with the big integers.
Here's the modified code.
#include <iostream>
#include <gmpxx.h>
using namespace std;
mpz_class getFactorial(int);
int main(int argc, char **argv) {
int num = 100;
mpz_class factorial = getFactorial(num);
cout << "Factorial of " << num << ": " << factorial << endl;
return 0;
}
mpz_class getFactorial(int num) {
int i;
mpz_class factorial = 1;
for(i=1; i<=num; i++) {
factorial *= i;
}
return factorial;
}
In order to use the gmp
library, I included the <gmpxx.h>
header file. Next I changed the data type of the factorial
variable and the return type of the getFactorial()
function from unsigned long long
to mpz_class
which is the data type that represents the big integer.
After modifying the code, I compiled with GCC using the following flags.
$gcc test.cpp -lstdc++ -lgmpxx -lgmp -o test
The -lgmpxx
and -lgmp
flags are required to compile the code using the gmp
library.
Now it works fine.
Upvotes: 2