南桥杯算法训练-P0505

版权声明:Dream_dog专属 https://blog.csdn.net/Dog_dream/article/details/86697380

一个整数n的阶乘可以写成n!,它表示从1到n这n个整数的乘积。阶乘的增长速度非常快,例如,13!就已经比较大了,已经无法存放在一个整型变量中;而35!就更大了,它已经无法存放在一个浮点型变量中。因此,当n比较大时,去计算n!是非常困难的。幸运的是,在本题中,我们的任务不是去计算n!,而是去计算n!最右边的那个非0的数字是多少。例如,5!=1*2*3*4*5=120,因此5!最右边的那个非0的数字是2。再如,7!=5040,因此7!最右边的那个非0的数字是4。再如,15!= 1307674368000,因此15!最右边的那个非0的数字是8。请编写一个程序,输入一个整数n(0<n<=100),然后输出n!最右边的那个非0的数字是多少。
输入:
  7
输出:
  4


题解:每次累乘前去掉末尾的0,值得注意的时候得到的值要保留在4左右,因为可能会出现一个单数去乘出现末尾为0的情况


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<bitset>
#include<stack>
#include<vector>
#include<cstring>
#include<string>
#include<map>
#include<cmath>
#include<sstream>
#define clr(a,b) memset(a,b,sizeof(a))
#define pb(a)    push_back(a)
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f3f3f;
const ll maxn=1000000000000+2;
const int minn=100;

ll solve(ll n)
{
    ll ans=1;
    for(int i=1;i<=n;++i)
    {
          ans*=i;
          while(ans%10==0){ans/=10;}
          //cout<<ans<<endl;
          ans%=10000;
    }
    return ans;
}
int main()
{
    // freopen("input12.txt","r",stdin);
    //int t=1;
     ll n;


    while(~scanf("%lld",&n))
    {
        printf("%lld\n",solve(n)%10);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dog_dream/article/details/86697380