Hello everbody,
I am given an integer n that can be at most 10^8. Now, I have to calculate the factorial of that number. I have been struggling with this problem for 2 days now. Can somebody help me? :)
Thanks!
Hey, thanks for your replies. No, I'm not after the project euler problem. I got confused, sorry. n can be at most 10^3 not 10^8, you are right that number is way too large.
Yep, I know.
I was thinking of creating a vector<int> and incrementally multiply the contents in ascending order of the products of n!. But I think this is very slow.
Thanks for your answer, againtry. Unfortunately, I cannot use python (I am not just playing around out of interest). It has to be c++ and I need to display that number.
#include <iostream>
#include <iomanip>
#include <vector>
usingnamespace std;
constint MOD = 1000000000; // the square of this has to be small enough to fit in unsigned long long
constint WMOD = 9; // width of field per "big digit" (up to MOD - 1)
class BigInt
{
public:
vector<unsignedlonglong> digits; // digits stored in REVERSE order;
BigInt( unsignedlonglong n = 0 ); // construct from integer
};
//------------------
BigInt::BigInt( unsignedlonglong n )
{
digits.clear();
if ( n == 0 )
{
digits.push_back( 0 );
}
else
{
while ( n )
{
digits.push_back( n % MOD );
n /= MOD;
}
}
}
//------------------
BigInt operator * ( const BigInt &a, const BigInt &b )
{
BigInt result = 0;
int asize = a.digits.size();
int bsize = b.digits.size();
for ( int i = 0; i < asize; i++ ) // Multiply by the ith digit of a and i tens
{
unsignedlonglong carry = 0;
for ( int j = 0; j < bsize || carry > 0; j++ )
{
if ( i + j < result.digits.size() ) carry += result.digits[i+j];
if ( j < bsize ) carry += a.digits[i] * b.digits[j];
unsignedlonglong digit = carry % MOD;
carry /= MOD;
if ( i + j < result.digits.size() ) result.digits[i+j] = digit;
else result.digits.push_back( digit );
}
}
return result;
}
//------------------
ostream &operator << ( ostream &out, const BigInt &a )
{
out << a.digits.back();
for ( int i = a.digits.size() - 2; i >= 0; i-- ) out << setw( WMOD ) << setfill( '0' ) << a.digits[i];
return out;
}
//======================================================================
int main()
{
constint N = 1000;
BigInt fac = 1;
for ( int n = 2; n <= N; n++ )
{
fac = fac * BigInt( n );
}
cout << fac << '\n';
}