uva 568 - Just the Facts

本文介绍了一种高效计算大数阶乘尾数的方法,通过两种不同的算法实现:一种利用数组存储中间结果并进行模运算;另一种使用数论模版简化计算过程。这两种方法都避免了直接计算大数带来的效率问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ps:重新看了一下题目,发现zoj的n没限制。。。而uva跟poj却限制到10000以内,所以前一个做法的预处理不一定够大,还是第二个方法强悍啊

不得不说,因为这题,我知道了poj的数据很水。。zoj这题过不了,uva却过了。

//不懂,觉得大数会超时,上网搜,题解 //f(i)=f(i-1)*i%10,i%5=0; //f(i)=mod(2,(n-1)%4+1))*f(n)%10,i%5!=0,n=i/5; //mod(2,(n-1)%4+1))的取值范围是2,4,6,8 #include <iostream> #include <cmath> #include <stdio.h> #include <string> using namespace std; //#define TEST long a[10001]={0, 1, 2, 6, 4, 2},b[5]={0, 2, 4, 8, 6}; int main() { #ifdef TEST freopen("input.txt", "r", stdin); #endif long m , n; for(long i = 6; i <= 10000; i++){ m = i % 5; n = i / 5; if(m != 0) a[i] = a[i - 1] * i % 10; else a[i] = b[(n - 1) % 4 + 1] * a[n] % 10; } while(cin >> n) { printf("%5d -> %d/n", n, a[n]); } return 0; }

后来看数论模版看到了一个方法:

#include <iostream> #include <cmath> #include <stdio.h> #include <cstring> using namespace std; int lastdigit(char*buf) { const int mod[20]={1,1,2,6,4,2,2,4,2,8,4,4,8,4,6,8,8,6,8,2}; int len=strlen(buf),a[110],i,c,ret=1; if(len==1) return mod[buf[0]-'0']; for(i=0;i<len;i++) a[i]=buf[len-1-i]-'0'; for(;len;len-=!a[len-1]) { ret=ret*mod[a[1]%2*10+a[0]]%5; for(c=0,i=len-1;i>=0;i--) c=c*10+a[i],a[i]=c/5,c%=5; } return ret+ret%2*5; } int main() { char s[10]; while(cin >> s) { printf("%5s -> %d/n", s, lastdigit(s)); } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值