How to determine time complexity of this code ? I guess that modPow method is the most “expensive “.
import java.math.BigInteger;
public class FermatOne
{
public static void main(String[] args)
{
BigInteger a = new BigInteger ("2");
BigInteger k = new BigInteger ("15");
BigInteger c = new BigInteger ("1");
int b = 332192810;
BigInteger n = new BigInteger ("2");
BigInteger power;
power = a.pow(b);
BigInteger exponent;
exponent = k.multiply(power);
BigInteger mod;
mod = exponent.add(c);
BigInteger result = n.modPow(exponent,mod);
System.out.println("Result is ==> " + result);
}
}
Well this particular code deterministically runs in
O(1).However, in more general terms for arbitrary variables,
multiply()will run inO(nlog n)wherenis the number of bits.pow()method will run inO(log b)for smallaandb. This is achieved by exponentiation by squaring. For larger values, the number of bits gets large (linearly) and so the multiplication takes more time. I’ll leave it up to you to figure out the exact analysis.I’m not 100% about the details about
modPow(), but I suspect it runs similarly topow()except with the extramodat each step in the exponentiation by squaring. So it’ll still beO(log b)multiplications with the added benefit that the number of bits is bounded bylog mwheremis the mod.