This is the piece of code in Java.
import java.util.Scanner;
import java.math.*;
class power1 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
long a=in.nextLong();
BigInteger b=in.nextBigInteger();
long res=power(a,b);
System.out.println(res);
}
public static long power(long x,BigInteger n) {
int b=(int)(Math.pow(10,9)+7);
long m;
if (n.compareTo(BigInteger.ZERO)==0)
return 1;
if(n.compareTo(BigInteger.ONE)==0)
return x;
if ((n.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO)==0))
{
m = power(x,n.divide(BigInteger.valueOf(2)));
return (m * m)%b;
}
else return (x * power(x,n.subtract(BigInteger.valueOf(1)))%b);
}
}
This is should work for any value of b considering that its a BigInteger. But when i enter very large value of b ,i get errors as
Exception in thread "main" java.lang.StackOverflowError
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.BigInteger.remainderKnuth(Unknown Source)
at java.math.BigInteger.remainder(Unknown Source)
at java.math.BigInteger.mod(Unknown Source)
Is there a way to fix it?
n.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO)==0is better written as!n.testBit(0), andn.divide(BigInteger.valueOf(2))is better written asn.shiftRight(1). Performs much better.longvalue to aBigIntegerexponent, and only returning result as along? If the base is 1, result is 1 no matter the exponent. If base is 2, the result will overflow the supported range of alongresult for an exponent value of 63, and you hardly need aBigIntegerto that kind of value. For bases higher than 2, the result will overflowlongat even smaller exponent values. Your method makes no sense.