题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3549
一般算a^b是用这种方法
int pow( int a, int b )
{
int r = 1;
while( b-- )
r *= a;
return r;
}
时间复杂度为O(n)。
当b比较大时就不行了,需要使用快速幂方法,其实就是二分时间复杂度为O(logn)。
具体看例子如:5^7,c=1;
7=(111),每次7右移一位,c=c*5。如下表:
b | 7 | 3 | 1 | 0 |
c | 1 | 5^1 | 5^1*5^2 | 5^1*5^2*5^4 |
AC源代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#define LL long long
using namespace std;
const long long con=1000000000;
LL QuickM (LL a,LL b)//快速幂
{
if (a==0)
return 1;
LL num=1;
a=a%con;//都要取个模,不然会出错
while (b)
{
if (b%2)
num=(num*a)%con;//取模
a=(a*a)%con;//取模
b>>=1;
}
return num;
}
int main ()
{
LL m,n,i,j;
while (scanf ("%lld%lld",&m,&n)!=EOF)
{
LL sum=0,num=0;
for (i=1;i<=m;i++)
{
sum+=QuickM (i,n);
//sum=sum%con;
}
while (1)
{
if (sum%10!=0)
break;
num++;
sum/=10;
}
printf ("%lld\n",num);
}
return 0;
}