N的阶乘(大数运算)

  对于一个大数来说,一个数的阶乘是非常大的。同样,一个int类型的整数,它的阶乘可能会很大。就拿50来说,它的阶乘位数是65位,就已经远远超出了long long int类型的最大值。这个时候,就要通过字符串的方法来进行阶乘的运算。

 

1 * 2

s = 1*2 = 2, array[0] = 2, up = 0

2                  

  

 

1 * 2 * 3

s = 2*3 = 6, array[0] = 6, up = 0

6                  

  

 

1 * 2 * 3 * 4

 s = 6*4 = 24, array[0] = 4, up = 2, array[1] = 2

4 2                

 

 

#include 
using namespace std;
int main()
{
	int n, i, j;
	int array[10001] =  {0};
	array[0] = 1;
	cin >> n ;
	
	for( i = 2; i <= n; i++)
	{
		int up = 0;
		for( j = 0; j <= 10000; j++)
		{
			int s = array[j]*i+up;
			array[j] = s%10;
			up = s/10;
		}
	}
	
	for( j = 10000; j >= 0; j--)
		if( array[j] != 0)
		{
			for( j; j >= 0; j--)
				cout << array[j];
		}
	return 0;
}

 

你可能感兴趣的:(C/C++)