Java Number Power pow(int base, int exp)

Here you can find the source of pow(int base, int exp)

Description

Computes an exponent.

License

Open Source License

Parameter

Parameter Description
base the base of the power
exp the non-negative exponent to which to raise <code>base</code>

Exception

Parameter Description
ArithmeticException if <code>(exp &lt; 0)</code>

Return

base raised to the power of exp

Declaration

public static int pow(int base, int exp) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*  w ww .  jav a 2  s .c o  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

  1. pow(float[][] in)
  2. pow(int a, int b)
  3. pow(int a, int b, int modulus)
  4. pow(int b, int e)
  5. pow(int base, int exp)
  6. pow(int base, int exponent)
  7. pow(int base, int power)
  8. pow(int i, int pow)
  9. pow(int leftOp, int rightOp)