大数n!
发布时间:2020-12-14 02:49:06 所属栏目:大数据 来源:网络整理
导读:通常解决大数运算数据超出范围,溢出的问题。一般采用数组去模拟。求算n!可以看成是每次两个整数相乘的过程,因此可以模拟成大数相乘的过程。只是需要增加一些变量去存储中间的进位和当前位的数值。 #include iostreamusing namespace std;#define MAX_WEI 1
通常解决大数运算数据超出范围,溢出的问题。一般采用数组去模拟。求算n!可以看成是每次两个整数相乘的过程,因此可以模拟成大数相乘的过程。只是需要增加一些变量去存储中间的进位和当前位的数值。
#include <iostream> using namespace std; #define MAX_WEI 100000 int result[MAX_WEI]; int wei_location; int up; int main() { int i,n; int j; while(scanf("%d",&n)!=EOF) { memset(result,sizeof(result)); result[1] =1; wei_location=1; //当前结果的位数,便于相乘和最后输出 up =0; if(n==0 || n==1) { printf("1n"); continue; } for(i=2;i<=n;i++) //n!中的每个数 { for(j =1,up =0;j<=wei_location;j++) //模拟乘法步骤:每一位与当前数相乘 { result[j] = result[j] *i + up; //当前数+前面的进位数 up = result[j]/10; result[j] =result[j]%10; //每个数存一位 } while(up > 0) { result[j++] += up%10; //注意跳出来是j是多一的 up= up/10; } wei_location= j -1;//注意跳出来是j是多一的 } for(i = wei_location;i>=1;i--) (i!=1)? printf("%d",result[i]) : printf("%dn",result[i]); } return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |