HDU1097——A hard puzzle题解及感想
A hard puzzle
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 54861 Accepted Submission(s): 20152
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进行递归调用,到了b == 1停止递归,来进行快速幂。由于若b为奇数,则 ab == ab/2 * ab/2 * a,若为偶数则是ab == ab/2 * ab/2,很简单就完成了。但是在里面一个关键的地方最容易被忽视掉——数据大小,题目给的数据大小最大230仍然是在int范围之内的,所以博主想当然的啥事没干就简简单单的把a直接读取就完事了,结果一上来WA。
后面才发现可能是a如果为230那么a * a就会爆,溢出了在怎么取模都是错误的,所以最好的办法就是把a %= 10,这样就可以实现了。做这种题一定要考虑数据范围的问题就像有时候a * b % 10会溢出,但 (a % 10) * (b % 10) % 10就不会溢出。这个地方要注意。
AC代码:
1 #include <stdio.h>
2 int sum;
3 void q(int a, int b)
4 {
5 if(b == 1)
6 return;
7 q(a, b / 2);
8 sum = sum * sum % 10;
9 if(b % 2 == 1)
10 sum = sum * (a % 10) % 10;
11 }
12
13 int main(void)
14 {
15 int a, b, n, num;
16 while(scanf("%d", &a) != EOF)
17 {
18 scanf("%d", &b);
19 sum = a % 10;
20 q(a, b);
21 printf("%d\n", sum);
22 }
23 return 0;
24 }
这样这道简单的水题就被AC了,当然还有一种解法叫打表,我猜肯定都会有循环,但是由于没办法证明,还是用了快速幂来解。