Skip to content

Conversation

DDullahan
Copy link
Contributor

Added FastPower

We may calculate power with loops, but what if the index is too large ?

FastPower aims to calculate quickly in this circumstances with time complexity O(log k), where k is the index.

Added FastPower
Copy link

@havanagrawal havanagrawal left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like the same functionality as modPow, so the tests should use this as the "expected" value.

public class FastPowerTest {

@Test
public void test() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should have assert* statements, not printlns.

BigInteger ans = BigInteger.ONE;
while (!k.equals(BigInteger.ZERO)) {
int odd = k.mod(new BigInteger("2")).compareTo(BigInteger.ZERO);
if(odd == 1){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The result of compareTo should only be compared with 0, there is no guarantee that it will be 1, only that it may be negative, 0 or positive.

if(odd == 1){
ans = ans.multiply(n).mod(mod);
}
k = k.divide(new BigInteger("2"));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using new BigInteger("2") in a loop, we could declare it as a constant outside:

public static final BigInteger TWO = new BigInteger("2");

@DDullahan
Copy link
Contributor Author

Thanks for your review @havanagrawal , I have fixed these problems.

@yanglbme yanglbme merged commit 64bd1a1 into TheAlgorithms:Development May 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants