HDU1061 Rightmost Digit 快速幂 C语言

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1061

题目大意:求n^n的最右位。

提交情况:n次WA。

总结:记得每次都要取模,否则会溢出。特殊当 n== 0,输出1。

思路:快速幂求n^n,每运算一次要模10。

 

AC code:

View Code
 1 #include <cstdio>
2
3 #include <cstdlib>
4
5 #define I64 __int64
6
7
8
9 int Fuction(I64 n) {
10
11 int res = 1;
12
13 I64 b = n;
14
15 if(!n) // n==0, 输出1
16
17 return 1;
18
19 if(!(n % 10))
20
21 return 0;
22
23 while(b) {
24
25 if(b & 1) {
26
27 res *= n;
28
29 res %= 10; // 要取模,否则溢出
30
31 }
32
33 n *= n;
34
35 n %= 10; // 要取模,否则溢出
36
37 b >>= 1;
38
39 }
40
41 return res % 10;
42
43 }
44
45
46
47 int main() {
48
49 int t;
50
51 I64 n;
52
53 scanf("%d", &t);
54
55 while(t--) {
56
57 scanf("%I64d", &n);
58
59 printf("%d\n", Fuction(n));
60
61 }
62
63 return 0;
64
65 }
posted @ 2011-07-20 16:26  cloehui  阅读(278)  评论(0编辑  收藏  举报