微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

nyoj28 大数阶乘 亿进制优化

          思路:刚开始用的十进制模拟手算加法,超时了。然后想到刘汝佳大哥书上面用的亿进制能够加速大数运算,果然180ms过掉了.

        亿进制与十进制相同,只不过是把八位看做一位,例如6464654654165,看成亿进制就是64646,54654165,这样运算时可以同时计算八位,快了很多。当然,想更快可以使用更高的进制,但注意不要超出long long范围

AC代码

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int,int> 
typedef long long LL;
const int maxn = 1e4 + 5,base = 100000000;
int res[maxn];
int len;

int main() {
	int n;
	while(scanf("%d",&n) == 1) {
		memset(res,sizeof(res));
		res[0] = 1;
		len = 1;
		for(int i = 2; i <= n; ++i) {
			int g = 0; 
			for(int j = 0; j < len || g > 0; ++j) {
				LL x = (LL)i * res[j] + g;
				res[j] = (int)(x % base);
				g = int(x / base);  //进位标记
				len = max(j+1,len); //更新结果的长度
			}
		}
		for(int i = len-1; i >= 0; --i) {
			if(i == len-1) printf("%d",res[i]);
			else printf("%08d",res[i]);
		}
		printf("\n");
	}
	return 0;
} 
如有不当之处欢迎指出!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐