Skip to content

Commit 7216f28

Browse files
committed
Added FastPower
Added FastPower
1 parent e4827bd commit 7216f28

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package src.main.java.com.Others;
2+
3+
import java.math.BigInteger;
4+
5+
/**
6+
* We may calculate power with loops, but what if the index is too large ?
7+
* FastPower aims to calculate quickly in this circumstances with time complexity O(log k),
8+
* where k is the index.
9+
*
10+
* @author DDullahan
11+
*/
12+
public class FastPower {
13+
public static BigInteger calculate(BigInteger n, BigInteger k, BigInteger mod) {
14+
BigInteger ans = BigInteger.ONE;
15+
while (!k.equals(BigInteger.ZERO)) {
16+
int odd = k.mod(new BigInteger("2")).compareTo(BigInteger.ZERO);
17+
if(odd == 1){
18+
ans = ans.multiply(n).mod(mod);
19+
}
20+
k = k.divide(new BigInteger("2"));
21+
n = n.multiply(n).mod(mod);
22+
}
23+
return ans.mod(mod);
24+
}
25+
26+
public static long calculate(long n, long k, long mod) {
27+
long ans = 1;
28+
while (k != 0) {
29+
if (k % 2 == 1) {
30+
ans = (ans * n) % mod;
31+
}
32+
k >>= 1;
33+
n = (n * n) % mod;
34+
}
35+
return ans % mod;
36+
}
37+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package src.main.java.com.Others;
2+
3+
import org.junit.*;
4+
5+
import java.math.BigInteger;
6+
7+
import static org.junit.Assert.*;
8+
9+
public class FastPowerTest {
10+
11+
@Test
12+
public void test() {
13+
System.out.println("Long Type:");
14+
long result;
15+
result = FastPower.calculate(2, 2, 10);
16+
assertEquals(result, 4);
17+
System.out.println("The result of power(2,2) mod 10 is " + result);
18+
19+
result = FastPower.calculate(100, 1000, 20);
20+
assertEquals(result, 0);
21+
System.out.println("The result of power(100, 1000) mod 20 is " + result);
22+
23+
result = FastPower.calculate(123456, 123456789, 234);
24+
System.out.println("The result of power(123456, 123456789) mod 234 is " + result);
25+
26+
27+
System.out.println("BigInteger Type:");
28+
BigInteger bigResult;
29+
bigResult = FastPower.calculate(BigInteger.TEN, BigInteger.TEN, new BigInteger("4"));
30+
assertEquals(bigResult, BigInteger.ZERO);
31+
System.out.println("The bigResult of power(10, 10) mod 4 is " + bigResult);
32+
33+
bigResult = FastPower.calculate(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234"));
34+
System.out.println("The bigResult of power(123456, 123456789) mod 234 is " + bigResult);
35+
36+
bigResult = FastPower.calculate(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890"));
37+
System.out.println("The bigResult of power(123456789101112, 12345678910111213) mod 567890 is " + bigResult);
38+
39+
}
40+
}

0 commit comments

Comments
 (0)