Factorial calculation and optimization

Any natural number n factorial representation method greater than 1: n!=1×2×3×……×n 

Code: 

# include<iostream>
# include<algorithm>

using namespace std;

//计算阶乘 ,递归定义 
long long fac0(int n){
	//计算到25 
	if(n <= 1)
		return 1;
	return n*fac0(n-1);
}

//优化算法
/*
思路就是模拟数学运算,从低位算到高位,将计算结果按位依次存储到数组中,然后逆序输出 
*/
void print_fac(int n){
	if(n <= 0)
		cout << "1" << endl;
	else
	{
		int a[500000] = {0,1};//a[0]用不上,将其他初始化为1
		int carry,length = 1,tmp;
		//carry:若有进位,存储若无,0 
		//length:若有进位,继续计算,若无默认计算一次
		//tmp:存储当前位的计算结果
		for(int i = 2;i <= n;++i){
			carry = 0;
			for(int j = 1;j <= length;++j){
				tmp = a[j] * i + carry;
				a[j] = tmp % 10;
				carry = tmp / 10;
				
				if(j == length && carry)
				length++;
			}	
		}
		
		for(int i = length;i >= 1;--i)
			cout << a[i];
	 } 
	 
} 

int main()
{
	int n;
	
	cin >> n;
	print_fac(n);

 return 0;
}

Through the running results, you can see that by definition (ie recursive), it can only count up to 25

After the improved algorithm, it can be seen that there is no collapse after the calculation reaches 70,000, which is enough for the general competition.

 

 

Guess you like

Origin blog.csdn.net/qq_40479037/article/details/87522118