power of BigInteger - Java java.math

Java examples for java.math:BigInteger

Description

power of BigInteger

Demo Code


//package com.java2s;
import java.math.BigInteger;

public class Main {
    public static void main(String[] argv) throws Exception {
        BigInteger base = new BigInteger("1234");
        long exponent = 2;
        System.out.println(pow(base, exponent));
    }/*from  w w w.  j a  v a2  s .c o m*/

    public static BigInteger pow(BigInteger base, long exponent) {
        return pow(base, BigInteger.valueOf(exponent));
    }

    public static BigInteger pow(BigInteger base, BigInteger exponent) {
        if (exponent.compareTo(BigInteger.ZERO) < 0) {
            throw new ArithmeticException("TODO: Write description");
        }
        BigInteger value = BigInteger.ONE;
        BigInteger multiple_special = base;
        while (!BigInteger.ZERO.equals(exponent)) {
            if (exponent.testBit(0)) {
                value = value.multiply(multiple_special);
            }
            multiple_special = multiple_special.multiply(multiple_special);
            exponent = exponent.shiftRight(1);
        }
        return value;
    }
}

Related Tutorials