USACO:Factorials

转载自So You Try的博客
Factorials

The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bit integer on most computers, and 70! is too large for most floating-point variables. Your task is to find the rightmost non-zero digit of n!. For example, 5! = 1 * 2 * 3 * 4 * 5 = 120, so the rightmost non-zero digit of 5! is 2. Likewise, 7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040, so the rightmost non-zero digit of 7! is 4.

PROGRAM NAME: fact4

INPUT FORMAT

A single positive integer N no larger than 4,220.

SAMPLE INPUT (file fact4.in)

7

OUTPUT FORMAT

A single line containing but a single digit: the right most non-zero digit of N! .

SAMPLE OUTPUT (file fact4.out)

4
 
把每个数分解质因数
因为2*5之后会产生一个零一直在右边,所以直接把2和5的个数同时减小,直到其中一个不存在(对答案无影响)
把所有质因数边乘边模


 
 
  1. #include<cstdio>  
  2. #include<cstring>  
  3. #include<cmath>  
  4. #include<iostream>  
  5. #include<algorithm>  
  6. #define name "fact4"  
  7. using namespace std;  
  8. int n,ans=1;  
  9. int cnt[5000];  
  10. void fenjie(int x)  
  11. {  
  12.     int i=2;  
  13.     while (x!=0&&x!=1)  
  14.     {  
  15.         while (x%i==0)   
  16.         {  
  17.             cnt[i]++;  
  18.             x/=i; 
  19.             if (x==0) break;  
  20.         }  
  21.         i++;  
  22.     }  
  23. }  
  24. int main()  
  25. {  
  26.     freopen(name ".in","r",stdin);  
  27.     freopen(name ".out","w",stdout);  
  28.     cin>>n;  
  29.     int i,j;  
  30.     for (i=2;i<=n;i++)  
  31.         fenjie(i);  
  32.     cnt[2]-=cnt[5];cnt[5]=0;  
  33.     for (i=2;i<=n;i++)  
  34.     {  
  35.         for (j=1;j<=cnt[i];j++)  
  36.         ans=(ans*i)%10;  
  37.     }  
  38.     cout<<ans<<endl;  
  39.     return 0;  
  40. }  
  41. /* 
  42. Executing... 
  43.    Test 1: TEST OK [0.000 secs, 4196 KB] 
  44.    Test 2: TEST OK [0.000 secs, 4196 KB] 
  45.    Test 3: TEST OK [0.000 secs, 4196 KB] 
  46.    Test 4: TEST OK [0.000 secs, 4196 KB] 
  47.    Test 5: TEST OK [0.000 secs, 4196 KB] 
  48.    Test 6: TEST OK [0.000 secs, 4196 KB] 
  49.    Test 7: TEST OK [0.000 secs, 4196 KB] 
  50.    Test 8: TEST OK [0.000 secs, 4196 KB] 
  51.    Test 9: TEST OK [0.000 secs, 4196 KB] 
  52.    Test 10: TEST OK [0.000 secs, 4196 KB] 
  53.  
  54. All tests OK. 
  55. YOUR PROGRAM ('fact4') WORKED FIRST TIME!  That's fantastic 
  56. -- and a rare thing.  Please accept these special automated 
  57. congratulations. 
  58. */  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值