A hard puzzle
Problem Description
lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius: gave a and b,how to know the a^b.everybody objects to this BT problem,so lcy makes the problem easier than begin.
this puzzle describes that: gave a and b,how to know the a^b's the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.
this puzzle describes that: gave a and b,how to know the a^b's the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.
Input
There are mutiple test cases. Each test cases consists of two numbers a and b(0<a,b<=2^30)
Output
For each test case, you should output the a^b's last digit number.
Sample Input
7 66 8 800
Sample Output
9 6
题目意思:求a^b的最后一位数,问题转化成a^b%10,代码如下:
#include<cstdio>
int mod(int a,int b,int k){
int ans=1;
a=a%k;
while(b>0){
if(b%2==1) ans=(ans*a)%k;
b/=2;
a=(a*a)%k;
}
return ans;
}
int main(){
int a,b;
while(scanf("%d%d",&a,&b)==2)
printf("%d\n",mod(a,b,10));
return 0;
}
这是直接的求法。看别人的题解,竟然还有一个规律:
尾数为0,1,5,6的不管是多少次方尾数依然不变,而尾数为4和9的每2次循环,
2,3,7,8为每4次循环。循环结果如下:
0,1,5,6:位数永远是0,1,5,6
2:6,2,4,8循环
3:1,3,9,7循环
4:6,4循环
7:1,7,9,3循环
8:6,8,4,2循环
9:1,9循环
好的,可以水过
了:
#include<cstdio>
int div[10]={1,1,4,4,2,1,1,4,4,2};
int f[10][4]={{0},{1},{6,2,4,8},{1,3,9,7},{6,4},{5},{6},{1,7,9,3},{6,8,4,2},{1,9}};
int main(){
int a,b;
while(scanf("%d%d",&a,&b)==2)
printf("%d\n",f[a%10][b%div[a%10]]);
return 0;
}