http://acm.nyist.net/JudgeOnline/problem.php?pid=473
-
输入
- There are mutiple test cases. Each test cases consists of two numbers a and b(0<=a,b<2^30) 输出
- For each test case, you should output the a^b's last digit number. 样例输入
-
7 66 8 800
样例输出
-
9 6
提示
- There is no such case in which a = 0 && b = 0。
简述之,就是求a^b的最低位。
思路:既然是求最低位,那么肯定就只与a的最低位有关了
a %= 10; /*取a的最低位*/
求一个数的N次方那么它的尾数会不会有规律呢,我们来试试
对于a的尾数(b不为0)
为0时,a^b的尾数为0....
为1时,a^b尾数为 1;
为2时,a^b尾数为2,4,8,6, 2,4,8,6.....
为3时,a^b的尾数为3,9,7,1, 3,9,7,1....
为4时,a^b的尾数为4,6,4,6, 4,6,4,6,4....
为5时,a^b的尾数为5,5,5,5, 5,5....
为6时,a^b的尾数为6,6,6,6, 6,6,6....
为7时,a^b的尾数为7,9,3,1, 7,9,3.1....
为8时,a^b的尾数为8,4,2,6, 8,4,2,6....
为9时,a^b的尾数为9,1,9,1,9, 1,9,1,9....
为了统一,我们都可以看作是4次一个循环。
#include <stdio.h>
int main()
{
int a,b;
int i,s;
while(scanf("%d%d",&a,&b)!=EOF)
{
if(b==0)
printf("1\n");
else
{
a%=10;
b=b%4+4;
s=a;
for(i=1;i<b;i++)
s*=a; //模拟a^b,简化程序的运行
s%=10;//获取尾数
printf("%d\n",s);
}
}
return 0;
}
ACM答案
#include <stdio.h>
int ac[10][4]={{0,0,0,0},{1,1,1,1},{6,2,4,8},{1,3,9,7},{6,4,6,4},{5,5,5,5},{6,6,6,6},{1,7,9,3},{6,8,4,2},{1,9,1,9}};
int main()
{
int a,b;
while(~scanf("%d%d",&a,&b))
printf("%d\n",b?ac[a%10][b%4]:1);
return 0;
}