fixed problems of code review from @havanagrawal

7216f28cb3
This commit is contained in:
DDullahan 2019-05-03 08:56:07 +08:00
parent 7216f28cb3
commit c85caf50d6
2 changed files with 19 additions and 27 deletions

View File

@ -13,11 +13,11 @@ public class FastPower {
public static BigInteger calculate(BigInteger n, BigInteger k, BigInteger mod) {
BigInteger ans = BigInteger.ONE;
while (!k.equals(BigInteger.ZERO)) {
int odd = k.mod(new BigInteger("2")).compareTo(BigInteger.ZERO);
if(odd == 1){
int odd = k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO);
if(odd > 0){
ans = ans.multiply(n).mod(mod);
}
k = k.divide(new BigInteger("2"));
k = k.divide(BigInteger.valueOf(2));
n = n.multiply(n).mod(mod);
}
return ans.mod(mod);

View File

@ -8,33 +8,25 @@ import static org.junit.Assert.*;
public class FastPowerTest {
void testLong(long n, long k, long m){
long result = FastPower.calculate(n,k,m);
assertEquals(result, BigInteger.valueOf(n).modPow(BigInteger.valueOf(k), BigInteger.valueOf(m)).longValue());
}
void testBigInteger(BigInteger n, BigInteger k, BigInteger m){
BigInteger result = FastPower.calculate(n,k,m);
assertEquals(result, n.modPow(k,m));
}
@Test
public void test() {
System.out.println("Long Type:");
long result;
result = FastPower.calculate(2, 2, 10);
assertEquals(result, 4);
System.out.println("The result of power(2,2) mod 10 is " + result);
testLong(2,2,10);
testLong(100,1000,20);
testLong(123456,123456789,234);
result = FastPower.calculate(100, 1000, 20);
assertEquals(result, 0);
System.out.println("The result of power(100, 1000) mod 20 is " + result);
result = FastPower.calculate(123456, 123456789, 234);
System.out.println("The result of power(123456, 123456789) mod 234 is " + result);
System.out.println("BigInteger Type:");
BigInteger bigResult;
bigResult = FastPower.calculate(BigInteger.TEN, BigInteger.TEN, new BigInteger("4"));
assertEquals(bigResult, BigInteger.ZERO);
System.out.println("The bigResult of power(10, 10) mod 4 is " + bigResult);
bigResult = FastPower.calculate(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234"));
System.out.println("The bigResult of power(123456, 123456789) mod 234 is " + bigResult);
bigResult = FastPower.calculate(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890"));
System.out.println("The bigResult of power(123456789101112, 12345678910111213) mod 567890 is " + bigResult);
testBigInteger(BigInteger.TEN,BigInteger.TEN, BigInteger.valueOf(4));
testBigInteger(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234"));
testBigInteger(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890"));
}
}