高精度计算N!
来源:互联网 发布:福建工程学院软件学院 编辑:程序博客网 时间:2024/04/30 03:57
计算N的阶乘,应用高精度计算,追求一题多解!(N<10000)
由于N是小于10000的,可以输入,则选择用INT型的大数即可,用数值型的高精度。
方法一:
#include <iostream>#include <cmath>#include <cstring>using namespace std;int main(){ const int maxn=50000; int n,c,k; int f[maxn+1]; while(cin>>n) { memset(f,0,sizeof(f)); f[0]=1; for(int i=1; i<=n; i++) { c=0;//代表进位 for(int j=0; j<=maxn; j++) { int s=f[j]*i+c; f[j]=s%10; c=s/10; } } for(k=maxn; k>=0; k--) if (f[k]!=0) break; for(int j=k; j>=0; j--) cout<<f[j]; cout<<endl; } return 0;}
可以把时间缩短为原来的一半的方法二:
在每一位上都存储一个五位数,采用同样的方法进行进位,只是在输出时需要注意即可。
#include <iostream>#include <cmath>#include <cstring>#include <cstdio>using namespace std;int main(){ const int maxn=20000; int n,c,k; int f[maxn+1]; while(cin>>n) { memset(f,0,sizeof(f)); f[0]=1; for(int i=1; i<=n; i++) { c=0;//代表进位 for(int j=0; j<=maxn; j++) { int s=f[j]*i+c; f[j]=s%100000; c=s/100000; } } for(k=maxn; k>=0; k--) if (f[k]!=0) break; cout<<f[k]; for(int j=k-1; j>=0; j--) printf("%05d",f[j]); cout<<endl; } return 0;}
速度更快的方法三:
每一次都记录当前数组中的结果的位数,可以使速度更快。
#include <iostream>#include <cmath>#include <cstring>#include <cstdio>using namespace std;int main(){ const int maxn=50000; int n,c,k; int f[maxn+1]; double wei; while(cin>>n) { wei=0; memset(f,0,sizeof(f)); f[0]=1; for(int i=1; i<=n; i++) { c=0;//代表进位 wei+=log10(i); int t=((int)wei+1)/5; for(int j=0; j<=t; j++) //控制计算次数 { int s=f[j]*i+c; f[j]=s%100000; c=s/100000; } } for(k=wei; k>=0; k--) if (f[k]!=0) break; cout<<f[k]; for(int j=k-1; j>=0; j--) printf("%05d",f[j]); cout<<endl; } return 0;}
阅读全文
0 0
- N!(高精度计算)
- 高精度计算N!
- 高精度计算-n的阶乘
- HDU1042 N! 高精度:计算n!精确值
- hdu - 1042 - N!(高精度计算)
- HDU 1042 N!(高精度计算阶乘)
- HDU 1042 N!(高精度计算阶乘)
- 高精度N!
- N!高精度
- N!高精度
- 九度OJ 1076:N的阶乘(高精度计算)
- 高精度计算,求一个小数的N次方(ACM1001)
- 高精度计算
- 高精度计算
- 高精度计算
- 高精度计算
- 高精度计算
- 高精度计算
- 解决编译“ Error: selected processor does not support ARM mode 'smc 0'”问题
- Partial Sum (2017湘潭)
- IOS越狱动态库相关-2017
- NoSuchBeanDefinitionException: No matching bean of type [com.piesat.web.service.SelectItemsService]
- 链接:蓝牙:蓝牙低功耗
- 高精度计算N!
- SHELL中的while循环
- intellij live template整理
- Macho文件浏览器---MachOView
- Cxf拦截器
- ios 实现android 中的DrawerLayout菜单
- Python标准模块——__future__
- 欢迎使用CSDN-markdown编辑器
- 反向传播算法入门资源索引