Calculate how many 0s at the end of the value below:
1n + 2n + 3n + ... + mn
Input
There are multiple cases. For each cases, the input containing two integers m, n. (1 <= m <= 100 , 1 <= n <= 1000000)
Output
One line containing one integer indicatint the number of 0s.
Sample Input
4 3
Sample Output
2
题意:求出1^n+2^n+3^n+……+m^n的值末尾的0的个数。
题目中m和n看起来很大,实际上用快速幂直接计算即可。用sum(long long)表示1^n+2^n+3^n+……+m^n的值,再求出sum末尾0的个数即可。
注意点1:快速幂取模,模值为1000000000(10^9)(估计答案最大不会大于9个0)
注意点2:sum求和过程中不要取模,否则会WA(应该有组数据正好有9个0,取模会导致sum为0)
注意点3:非递归快速幂时需要long long,不然会溢出
#include <iostream>
#include <cstdio>
using namespace std;
const int mod=1000000000;
int n,m;
long long Qmod(int x,int b)
{
long long res=1,a=x; //注意此处用long long来代替了底数,避免在a*a时溢出
while (b)
{
if (b&1) res=res*a%mod;
a=a*a%mod;
b>>=1;
}
return res;
}
int main()
{
while (scanf("%d%d",&m,&n)!=EOF)
{
long long sum=0;
for (int i=1;i<=m;i++)
{
sum=sum+Qmod(i,n); //此处不要加上%mod,否则会WA
}
int ans=0;
while (sum%10==0&&sum>0)
{
++ans;
sum/=10;
}
printf("%d\n",ans);
}
return 0;
}