首页 > 其他 > 详细

阶乘最后非零位

时间:2014-08-04 14:12:27      阅读:303      评论:0      收藏:0      [点我收藏+]

Last non-zero Digit in N! http://acm.hdu.edu.cn/showproblem.php?pid=1066

bubuko.com,布布扣
 1 #include<cstdio>
 2 #include<cstring>
 3 const int M=1024;
 4 const int tomod[20]= {1,1,2,6,4,2,2,4,2,8,4,4,8,4,6,8,8,6,8,2};
 5 int lastdigit(char buf[]){//阶乘最后非0位O(nlogn)返回该位,n以字符串方式传入
 6     int len=strlen(buf),ret=1,a[M];
 7     if(len==1) return tomod[buf[0]-0];
 8     for(int i=0;i<len;i++) a[i]=buf[len-1-i]-0;
 9     for(;len;len-=!a[len-1]){
10         ret=ret*tomod[a[1]%2*10+a[0]]%5;
11         for(int c=0,i=len-1;i>=0;i--){
12             c=c*10+a[i];
13             a[i]=c/5;
14             c%=5;
15         }
16     }
17     return ret+ret%2*5;
18 }
19 char str[M];
20 int main() {
21     while(~scanf("%s",str)) {
22         printf("%d\n",lastdigit(str));
23     }
24     return 0;
25 }
View Code

 

 

 

end

阶乘最后非零位,布布扣,bubuko.com

阶乘最后非零位

原文:http://www.cnblogs.com/gaolzzxin/p/3889945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!