Java Number Power pow(int n, int p)

Here you can find the source of pow(int n, int p)

Description

pow

License

Open Source License

Declaration

public static int pow(int n, int p) 

Method Source Code

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

public class Main {

    public static int pow(int n, int p) {
        if (p < 0) {
            throw new ArithmeticException("p cannot be negative. Invalid p: " + p);
        }/* w  ww .  ja  va  2 s .  co  m*/
        if (p == 0)
            return 1;
        if (n == 0)
            return 0;
        if (n == 1)
            return 1;
        if (n == 2) {
            if (p > 30) {
                throw new ArithmeticException("n^p must be less than 2^31. n: " + n + ", p: " + p);
            }
            return 1 << p;
        }
        if (n == -2) {
            if (p == 31)
                return Integer.MIN_VALUE;
            if (p > 31) {
                throw new ArithmeticException("n^p must be greater than or equal to -2^31. n: " + n + ", p: " + p);
            }
            int result = 1 << p;
            return (p & 1) == 0 ? result : -result;
        }
        int result = 1;
        for (int i = 0; i < p; i++) {
            result = Math.multiplyExact(result, n);
        }
        return result;
    }
}

Related

  1. pow(int base, int exp)
  2. pow(int base, int exponent)
  3. pow(int base, int power)
  4. pow(int i, int pow)
  5. pow(int leftOp, int rightOp)
  6. pow(int number, int power)
  7. pow(int value, int exp)
  8. pow(int x, int y)
  9. pow(int[] arr, double p)