1104: 那些年,我们一起无聊过
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 167 Solved: 35
[ Submit][ Status][ Web Board]
Description
提问:求x^y的各位数字和的各位数字和的各位数字和的各位数字和。
Input
第一行一个整数T<=100
以下T行,每行两个整数x,y,其中0<=x,y<=100000。
输入保证没有0^0的情况。
Output
对于每组测试数据,按照题目要求输出一行表示结果。
Sample Input
3
2 1
2 5
2 8
Sample Output
2
5
4
HINT
对于样例的第三组测试数据,2^8 = 256,其各位数字和2+5+6=13,13的各位数字和为4,4的各位数字和为4,4的各位数字和为4。
虽然BigInteger可以很轻易的求出x^y的精确结果,但是请仔细思考本题数据范围和时限。
思路:先考虑x,y各为0的情况,再将x%9,然后将y化作二进制,快速幂乘法。
AC代码如下:
#include<cstdio>
#include<cstring>
using namespace std;
long long t,a,b,i,j,ans;
void solve()
{ if(b)
{ if(b%2==0)
{ b/=2;
solve();
ans=ans*ans;
ans%=9;
if(ans==0)
ans=9;
}
else
{ b/=2;
solve();
ans=ans*ans*a;
ans%=9;
if(ans==0)
ans=9;
}
}
}
int main()
{ scanf("%lld",&t);
while(t--)
{ scanf("%lld%lld",&a,&b);
if(a==0)
{ printf("0\n");continue;}
if(b==0)
{ printf("1\n");continue;}
if(a>9)
{ a=a%9;
if(a==0)
a=9;
}
ans=1;
solve();
printf("%lld\n",ans);
}
}