Here you can find the source of pow(int base, int exp)
Parameter | Description |
---|---|
base | the base of the power |
exp | the non-negative exponent to which to raise <code>base</code> |
Parameter | Description |
---|---|
ArithmeticException | if <code>(exp < 0)</code> |
base
raised to the power of exp
public static int pow(int base, int exp)
//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 < 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; } }