// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.math.BigInteger;

public class BigPow {
    @FunctionalInterface
    public static interface F {
        public BigInteger calc(BigInteger b, int p);
    }
    public static BigInteger BigIntPowStd(BigInteger b, int p) {
        return b.pow(p);
    }
    public static BigInteger BigIntPow3(BigInteger b, int p)
    {
        if(p == 1) return b;
        if(p % 3 != 0) throw new RuntimeException("Ooops - " + p + " is not good");
        return BigIntPow3(b.multiply(b).multiply(b), p / 3);
    }
    public static BigInteger BigIntPow(BigInteger b, int p)
    {
        if(p == 1) return b;
        if(p % 3 == 0) return BigIntPow(b.multiply(b).multiply(b), p / 3);
        if(p % 2 == 0) return BigIntPow(b.multiply(b), p / 2); 
        return b.multiply(BigIntPow(b, p - 1));
    }
    public static void test(F f, BigInteger b, int p) {
        long t1 = System.currentTimeMillis();
        BigInteger res = f.calc(b, p);
        long t2 = System.currentTimeMillis();
        System.out.printf("%d bits (%.1f secs)\n", res.bitLength(), (t2 - t1) / 1000.0);
    }
    public static void main(String[] args) {
        int p = 9 * 9 * 9 * 9 * 9 * 9 * 9;// * 9 * 9; 
        BigInteger b = new BigInteger("9");
        test(BigPow::BigIntPowStd, b, p);
        test(BigPow::BigIntPow3, b, p);
        test(BigPow::BigIntPow, b, p);
    }
}
