杭电OJ1042——大数阶乘问题

题目: N!


Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!

Input
One N in one line, process to the end of file.

Output
For each N, output N! in one line.

Sample Input
1
2
3

Sample Output
1
2
6

  • 解决办法
    阶乘问题的解决方法,对于初学者的我们最先想到的可能是用for循环,或者用递归。这两种蛮力法,在int和long int范围内能容纳12及12以内阶乘的结果,在long long范围内能容纳最多20的阶乘。由此我们可以知道,20以上的阶乘结果我们根本无法用蛮力法直接算出来。
    以前每次遇到大数的阶乘问题就头疼,今天我终于学到了大数阶乘的算法。
    其实大数阶乘我们要解决的问题就是如何将超过longlong的数呈现出来。既然整个结果超出范围,那么我们就想办法将结果分成符合范围的几段,然后按段输出。

#include<stdio.h>
int main()
{
    
    
	int n;
	int arr[10001];
	while(~scanf("%d",&n))
	{
    
    
		int m=0,temp;
		int i,j;
		arr[0]=1;
		*//外层循环控制阶乘* 
		for(i=1;i<=n;i++)
		{
    
    
			temp=0;*//注意要更新进位数* 
			*//内层循环保证所有的数都有乘* 
			for(j=0;j<=m;j++)
			{
    
     
				arr[j]=arr[j]*i+temp;*//原位的数乘以阶乘对应的数+进位数* 
				*//每5位一进位* 
				temp=arr[j]/100000; 
				arr[j]=arr[j]%100000;
			}
			*/*倘若内层循环完了,还有进位剩余,
			则先将进位的数作为下一个5位数的基数*/* 
			if(temp!=0)
			{
    
    
				m++;
				arr[j]=temp;
			}
		}
		printf("%d",arr[m]); *//先将最高的几位打印出来,避免不足5位补0*
		*//每5位打印一次*
		for(i=m-1;i>=0;i--)
		{
    
    
			printf("%05d",arr[i]);
		}
		printf("\n");
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43846755/article/details/87642075
今日推荐