Precision Value of Factorial

来源:互联网 发布:软件需求分析说明书 编辑:程序博客网 时间:2024/06/01 14:22

Problem : Input an integer n that is equal or less than 1000, then output the factorial's precision value of n.

Solution : As we all known, the multiplication of two integer numbers can be computed as follows:

From the beginning of  units digit, units digit multiplies themultiplier and get a result. Then pick the units digit into the relative(unit digit) position of array from the result and pick the carry from the result. In the next step, replace the units digit with the tens digit and repeat the above steps until the last digit.

For example, given two integers 24 and 15, we know that the units digit of 24 is 4, so 4 multiplies 15 is 60. Then pick the units digit data of 60 (i.e., 0) into the first position of array, and pick out the carry(i.e.,6 ). At the same time, the tens 2 multiplies 15 is 30 and adds it to 6 (i.e., 36), then put the units digit data of 36 (i.e., 6) into the second position of array and pick the carray(i.e., 3), do it again using the above methods.

The source code can be writed as follows:

#include <iostream.h>#include <stdio.h>#include <string.h>const int maxn=3000;int f[maxn];int main(void){int i,j,n;cin>>n;memset(f,0,sizeof(f));//include the library of <string.h>f[0]=1;//initial the units digitfor(i=2;i<=n;i++){int c=0;//initial the carry c using zero.for(j=0;j<maxn;j++){int s=f[j]*i+c;//i multiplies each data digit of array f and plus the carry c f[j]=s%10;//pick the units digit of s.c=s/10;//pick the carry c of s(i.e., pick the remaining data but the units digit.)}}for(j=maxn-1;j>=0;j--) if(f[j])break;for(i=j;i>=0;i--) cout<<f[i];cout<<endl;return 0;}