Java Number Power powExact(long x, int y)

Here you can find the source of powExact(long x, int y)

Description

Returns value of x raised in power y, throwing an exception if the result overflows a long.

License

Open Source License

Parameter

Parameter Description
x base
y power

Exception

Parameter Description
ArithmeticException if the result overflows a long<br>or if x = 0 and y &lt; 0 (resulting in infinity)

Return

xy

Declaration

public static long powExact(long x, int y) throws ArithmeticException 

Method Source Code

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

public class Main {
    /**/* w  w  w  .  j  a  v a2 s.  c o  m*/
     * Returns value of x raised in power y, throwing an exception if the result overflows a long.
     * @param x base
     * @param y power
     * @return x<sup>y</sup>
     * @throws ArithmeticException if the result overflows a long<br>
     * or if x = 0 and y &lt; 0 (resulting in infinity)
     */
    public static long powExact(long x, int y) throws ArithmeticException {
        if (y >= 0) {
            long z = 1L;
            while (true) {
                if ((y & 1) != 0)
                    z = Math.multiplyExact(z, x);
                y >>>= 1;
                if (y == 0)
                    break;
                x = Math.multiplyExact(x, x);
            }
            return z;
        } else {
            if (x == 0L)
                throw new ArithmeticException("Negative power of zero is infinity");
            if (x == 1L)
                return 1L;
            if (x == -1L)
                return (y & 1) == 0 ? 1L : -1L;
            return 0L;
        }
    }

    /**
     * Returns value of x raised in power y, throwing an exception if the result overflows an int.
     * @param x base
     * @param y power
     * @return x<sup>y</sup>
     * @throws ArithmeticException if the result overflows an int<br>
     * or if x = 0 and y &lt; 0 (resulting in infinity)
     */
    public static int powExact(int x, int y) throws ArithmeticException {
        if (y >= 0) {
            int z = 1;
            while (true) {
                if ((y & 1) != 0)
                    z = Math.multiplyExact(z, x);
                y >>>= 1;
                if (y == 0)
                    break;
                x = Math.multiplyExact(x, x);
            }
            return z;
        } else {
            if (x == 0)
                throw new ArithmeticException("Negative power of zero is infinity");
            if (x == 1)
                return 1;
            if (x == -1)
                return (y & 1) == 0 ? 1 : -1;
            return 0;
        }
    }
}

Related

  1. powerString(int power)
  2. powerToInteger(String pow)
  3. powerTrim(String s)
  4. powerType(float power)
  5. powerX(long a, long b)
  6. powf(float v1, float v2)
  7. powi(double x, int p)
  8. powInt(int base, int exponent)
  9. powLLL(double[] a, double b)