Computes an exponent. - Java java.lang

Java examples for java.lang:Math Operation

Description

Computes an exponent.

Demo Code


//package com.java2s;

public class Main {
    /**//from w  w w .  j a v a2  s  .co  m
     * Computes an exponent.
     * 
     * <p>
     * The Math.pow method always returns a double--which is good for negative and rational exponents, but bad when we want an exact integral result that could be rendered void by floating-point round-off error. To correct for this, this method operates only on integers.
     * </p>
     * 
     * @param base the base of the power
     * @param exp the non-negative exponent to which to raise <code>base</code>
     * @return <code>base</code> raised to the power of <code>exp</code>
     * @throws ArithmeticException if <code>(exp &lt; 0)</code>
     */
    public static int pow(int base, int exp) {
        // Sanity and stupid tests
        if (exp < 0) { // then crazy things happen; we want integral results
            throw new ArithmeticException("exponent must be non-negative");
        }
        if (exp == 0) {
            return 1;
        }
        if (exp == 1) {
            return base;
        }
        if (exp == 2) {
            return base * base;
        }

        int ret = 1;
        while (exp != 0) {
            if ((exp & 1) != 0) {
                ret *= base;
            }
            exp >>= 1; // right-shift doesn't actually divide by 2 for negative numbers, but here it's OK due to sanity checks
            base *= base;
        }

        return ret;
    }
}

Related Tutorials