51nod1057 N的阶乘 压位

来源:互联网 发布:emily the strange淘宝 编辑:程序博客网 时间:2024/06/05 20:10

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1057

大数运算
阶乘
修改 隐藏话题
1057 N的阶乘
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
 收藏
 关注
输入N求N的阶乘的准确值。
Input
输入N(1 <= N <= 10000)
Output
输出N的阶乘
Input示例
5
Output示例
120

题意:求出N!

题解:一直没接触过这种类型的,以为需要大数的模板。结果看了别人的代码,用的巧妙的压位。其实也是大数的思路,大数加减乘除模板,是将一个长度为n的数划分成n位。我们这里也需要划分,如果是划分成一位。那么时间复杂度是不变的,只是解决了int的溢出问题。所以划分的大一点,即可以减少数组的开销,又可以降低时间复杂度。我还专门试了一下,这题最多可以划分的是14位。因为14+4就是18个0了,在不超过long long的基础上(最少可以通过的需要压4位,相当于10000进制)。然后这题压14位跑了140ms,4位的跑了468ms。

总结:压位多的可以减少运算次数,但是要避免溢出的前提下追求效率。

代码:

#include<set>#include<map>#include<stack>#include<queue>#include<vector>#include<string>#include<bitset>#include<algorithm>#include<cstring>#include<cstdio>#include<cmath>#include<iomanip>#include<iostream>#define debug cout<<"aaa"<<endl#define d(a) cout<<a<<endl#define mem(a,b) memset(a,b,sizeof(a))#define LL long long#define lson l,mid,root<<1#define rson mid+1,r,root<<1|1#define MIN_INT (-2147483647-1)#define MAX_INT 2147483647#define MAX_LL 9223372036854775807i64#define MIN_LL (-9223372036854775807i64-1)using namespace std;const int N = 1000000 + 5;const int mod = 1000000000 + 7;const double eps = 1e-8;LL ans[N];int main(){int n,cnt=0;int temp;mem(ans,0),ans[0]=1;scanf("%d",&n);for(int i=2;i<=n;i++){temp=0;//保存进位 for(int j=0;j<=cnt;j++){ans[j]=ans[j]*i+temp;temp=ans[j]/10000;//压4位 ans[j]%=10000;}if(temp){ans[++cnt]=temp;}}printf("%lld",ans[cnt]);//最高位for(int i=cnt-1;i>=0;i--){printf("%04lld",ans[i]);} puts(""); return 0;}


原创粉丝点击