Wednesday, July 1, 2009

1000 ! Factorial.

Large factorial is a problem for a single variable but for an array, the problem is solved easily :D

#include <iostream>
#include <cmath>
#include <vector>

struct factorial {
factorial( unsigned x ):x( x ), digits( static_cast< int >( cal_digs( x ) ) + 1, 0 ) {
find_fact();
}

double cal_digs( unsigned N ) {
double appr = 0.0;
for( unsigned di = 2; di <= N; ++di )
appr += std::log10( di );
return appr;
}

void find_fact() {
unsigned rem, tmp, val;
digits.at( 0 ) = 1;
double appr = 0.0;
for( unsigned o = 2; o <= x; ++o ) {
rem = 0;
appr += std::log10( o );
tmp = static_cast< unsigned >( appr );
for( unsigned o1 = 0; o1 <= tmp; ++o1 ) {
val = ( digits.at( o1 ) * o ) + rem;
rem = val / 10;
digits.at( o1 ) = val % 10;
}
}
}

std::ostream& out( std::ostream& o ) const {
for( std::vector< unsigned >::const_reverse_iterator cib = digits.rbegin(), cie = digits.rend(); cib != cie; ++cib )
o << *cib;
return o << std::endl;
}

private :
unsigned x;
std::vector< unsigned > digits;
};

std::ostream& operator <<( std::ostream& o, const factorial& fa ) {
return fa.out( o );
}

int main()
{
factorial f( 10000 );
std::cout << f << "\n";
}

No comments:

Post a Comment