forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastPower.java
More file actions
91 lines (69 loc) · 1.88 KB
/
FastPower.java
File metadata and controls
91 lines (69 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package Algorithms.lintcode.math;
class FastPower {
public static void main(String[] strs) {
System.out.println(fastPower(2147483647, 2147483645, 214748364));
//System.out.println(Math.pow(2, 2147483647));
System.out.println(9 % (-2));
}
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public static int fastPower(int a, int b, int n) {
// write your code here
long ret = pow(a, b, n);
return (int) ret;
}
// suppose n > 0
public static long pow1(int a, int b, int n) {
if (a == 0) {
return 0;
}
// The base case.
if (n == 0) {
return 1 % b;
}
if (n == 1) {
return a % b;
}
long ret = 0;
// (a * b) % p = (a % p * b % p) % p (3)
ret = pow(a, b, n / 2);
ret *= ret;
// 这一步是为了防止溢出
ret %= b;
if (n % 2 == 1) {
ret *= pow(a, b, 1);
}
// 执行取余操作
ret = ret % b;
return ret;
}
// SOLUTION 2:
// suppose n > 0
public static long pow(int a, int b, int n) {
if (a == 0) {
return 0;
}
// The base case.
if (n == 0) {
return 1 % b;
}
long ret = 0;
// (a * b) % p = (a % p * b % p) % p (3)
ret = pow(a, b, n / 2);
ret *= ret;
// 这一步是为了防止溢出
ret %= b;
if (n % 2 == 1) {
ret *= (a % b);
}
// 执行取余操作
ret = ret % b;
return ret;
}
};