103

Is there any other way in Java to calculate a power of an integer?

I use Math.pow(a, b) now, but it returns a double, and that is usually a lot of work, and looks less clean when you just want to use ints (a power will then also always result in an int).

Is there something as simple as a**b like in Python?

Neuron
  • 5,141
  • 5
  • 38
  • 59
Hidde
  • 11,493
  • 8
  • 43
  • 68

18 Answers18

63

When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent

example:

22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)

For larger exponents (over 31) use long instead

232 = 1L << 32 = (long) Math.pow(2, 32)

btw. in Kotlin you have shl instead of << so

(java) 1L << 32 = 1L shl 32 (kotlin)

Stanislaw Baranski
  • 1,308
  • 9
  • 18
61

Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.

If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.

Neuron
  • 5,141
  • 5
  • 38
  • 59
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 70
    +1, that's true. But I would consider it nice if the `Java` architects have added `pow(int, int)`. You know sometimes you just want that `5^6` and don't care about doubles at all. – Petar Minchev Nov 09 '11 at 20:50
  • 6
    I'm just guessing, but I think they didn't do it because such a method would lead to completely incorrect results in most of the cases. Principle of least astonishment. – JB Nizet Nov 09 '11 at 20:57
  • 3
    Yeah, that's a good point. But when you are an ignorant and you work with `int`, nothing stops you to convert to `(int)` an overflowed value. – Petar Minchev Nov 09 '11 at 20:59
  • 7
    I mean if you defined "most of the cases" as "for most value of the inputs" then Java should certainly not offer the `*` operator either for `int` or `long` inputs since for most inputs the multiplication will overflow. In fact, even addition overflows about half the time! – BeeOnRope Jun 02 '16 at 23:52
  • Sorry if I come in late. Why use double and not long? – Blueriver Sep 26 '17 at 02:28
  • Couldn't `long`s have solved this issue without having to go to floating point? – miguel Nov 01 '20 at 19:41
  • The max value of `double` is on the order of 10^308, while the max value for `long` is on the order of 10^19 - huge difference – marcotama Jun 17 '21 at 04:01
42

Best the algorithm is based on the recursive power definition of a^b.

long pow (long a, int b)
{
    if ( b == 0)        return 1;
    if ( b == 1)        return a;
    if (isEven( b ))    return     pow ( a * a, b/2); //even a=(a^2)^b/2
    else                return a * pow ( a * a, b/2); //odd  a=a*(a^2)^b/2

}

Running time of the operation is O(logb). Reference:More information

Laakal
  • 657
  • 6
  • 16
  • 3
    And what is `isEven(b)` method do? Is it same with `b % 2 == 0`? – HendraWD Jan 31 '18 at 04:58
  • 2
    I wonder too ... The guy has gone and left us wondering ... Slipshod programmers ... – Apostolos Aug 01 '18 at 11:31
  • Inexistent `(isEven(b))' function -- meaning `((b & 1) == 0)` -- and an unnecessary complicated algorithm! ( – Apostolos Aug 01 '18 at 15:21
  • 2
    Better handle case where b<0 to avoid infinite recurssion – Tzafrir Aug 17 '18 at 03:59
  • 8
    In my benchmarks, this is actually 2x to 20x slower than the [simple loop algorithm](https://stackoverflow.com/a/8071402) for the full range of values. The recursion here imposes a lot of overhead. – Gumby The Green Apr 27 '19 at 01:34
  • @Apostolos "unnecessary complicated algorithm". Well, no. It is the standard way to compute (integral) power efficiently. Optimized algorithms are not "unnecessary complicated algorithm[s]". See https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int for instance. – akim Dec 07 '22 at 16:42
38

No, there is not something as short as a**b

Here is a simple loop, if you want to avoid doubles:

long result = 1;
for (int i = 1; i <= b; i++) {
   result *= a;
}

If you want to use pow and convert the result in to integer, cast the result as follows:

int result = (int)Math.pow(a, b);
Kasun Siyambalapitiya
  • 3,956
  • 8
  • 38
  • 58
Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
  • 5
    @DmitryGinzburg: given a `long` is 64 bit, then O(n) has 64 as an upper limit. Is that really so bad? – Thomas Weller May 12 '15 at 08:58
  • 1
    @Thomas no, you're wrong; if `b` is `2_000_000_000`, then you'll have to do `2e9` operations instead of `31` in [other solution](http://stackoverflow.com/a/20984477/1828937) – Dmitry Ginzburg May 12 '15 at 09:01
  • 2
    @DmitryGinzburg: you'll get a lot of overflow problems in that case. The OP's code does not include argument validation. The maximum number allowed should be 64 in case a is as small as 2 (and for a=1 it doesn't make sense). – Thomas Weller May 12 '15 at 10:56
  • @Thomas overflow issues is not your problem, but problem of runner. – Dmitry Ginzburg May 12 '15 at 11:02
  • 2
    In my benchmarks, this is actually 2x to 20x faster than the recursive O(log(b)) algorithm for the full range of values. The recursion imposes a lot of overhead. – Gumby The Green Apr 27 '19 at 01:31
  • An alternative to the loop, but using streams, might look something like: `long result = LongStream.generate( () -> a ).limit(b).reduce( (i,j) -> i*j ).orElse(1);` The scope of the OP's question seems to be `b >= 0`, otherwise you need floats/doubles for the result of course. – pkeller Feb 03 '20 at 18:51
  • The maximum power you can sensibly raise an `int` to is 32, unless you specifically want overflow in order to compute the power modulo 2^32 (which is not likely). Similarly for `long`. Anyone trying to raise a primitive `int` or `long` to the power 2 billion is doing something silly. – kaya3 Feb 08 '20 at 06:12
9

Google Guava has math utilities for integers. IntMath

Community
  • 1
  • 1
ant
  • 151
  • 2
  • 2
4
import java.util.*;

public class Power {

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int num = 0;
        int pow = 0;
        int power = 0;

        System.out.print("Enter number: ");
        num = sc.nextInt();

        System.out.print("Enter power: ");
        pow = sc.nextInt();

        System.out.print(power(num,pow));
    }

    public static int power(int a, int b)
    {
        int power = 1;

        for(int c = 0; c < b; c++)
            power *= a;

        return power;
    }

}
cavpollo
  • 4,071
  • 2
  • 40
  • 64
2

Guava's math libraries offer two methods that are useful when calculating exact integer powers:

pow(int b, int k) calculates b to the kth the power, and wraps on overflow

checkedPow(int b, int k) is identical except that it throws ArithmeticException on overflow

Personally checkedPow() meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).

If you want get a long result, you can just use the corresponding LongMath methods and pass int arguments.

BeeOnRope
  • 60,350
  • 16
  • 207
  • 386
2

Well you can simply use Math.pow(a,b) as you have used earlier and just convert its value by using (int) before it. Below could be used as an example to it.

int x = (int) Math.pow(a,b);

where a and b could be double or int values as you want. This will simply convert its output to an integer value as you required.

  • 4
    I disagree, if `3.0 ^ 1.0 = 2.999999...` due to rounding errors, the answer will be `2` which is wrong. – Hidde Jul 05 '17 at 12:42
  • @Hidde Yes, you are right friend this certainly has a drawback, thanks for mentioning. It may give wrong result but probably your example here would give the correct result as `3.0`.Just as an example to rounding error for multiplication `2.2*3.0 = 6.0000005` rather than `6.6`. – Shubham Srivastava Jul 06 '17 at 14:45
  • 2
    @Hidde A Java `double` can represent all Java `ints` exactly. See the Java language specification, section 5.1.2, "[Widening Primitive Conversion](https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.1.2)". – David Moles Feb 07 '18 at 00:40
  • 3
    @David, Thanks, however my argument above still holds. The numbers itself will be exact representations but the result of the power may not be. Especially for large powers. – Hidde Feb 08 '18 at 06:28
  • 2
    @Hidde If the result of the power fits in an `int`, it will be exact. If it doesn't fit in an `int`, then decimal expansion is not your problem, overflows are your problem. – David Moles Feb 08 '18 at 18:25
2

A simple (no checks for overflow or for validity of arguments) implementation for the repeated-squaring algorithm for computing the power:

/** Compute a**p, assume result fits in a 32-bit signed integer */ 
int pow(int a, int p)
{
    int res = 1;
    int i1 = 31 - Integer.numberOfLeadingZeros(p); // highest bit index
    for (int i = i1; i >= 0; --i) {
        res *= res;
        if ((p & (1<<i)) > 0)
            res *= a;
    }
    return res;
}

The time complexity is logarithmic to exponent p (i.e. linear to the number of bits required to represent p).

Michail Alexakis
  • 1,405
  • 15
  • 14
1

I managed to modify(boundaries, even check, negative nums check) Qx__ answer. Use at your own risk. 0^-1, 0^-2 etc.. returns 0.

private static int pow(int x, int n) {
        if (n == 0)
            return 1;
        if (n == 1)
            return x;
        if (n < 0) { // always 1^xx = 1 && 2^-1 (=0.5 --> ~ 1 )
            if (x == 1 || (x == 2 && n == -1))
                return 1;
            else
                return 0;
        }
        if ((n & 1) == 0) { //is even 
            long num = pow(x * x, n / 2);
            if (num > Integer.MAX_VALUE) //check bounds
                return Integer.MAX_VALUE; 
            return (int) num;
        } else {
            long num = x * pow(x * x, n / 2);
            if (num > Integer.MAX_VALUE) //check bounds
                return Integer.MAX_VALUE;
            return (int) num;
        }
    }
Smarty77
  • 1,208
  • 3
  • 15
  • 30
1

base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).

public int power(int base, int n){
   return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
}
Morriss
  • 39
  • 6
1

There some issues with pow method:

  1. We can replace (y & 1) == 0; with y % 2 == 0
    bitwise operations always are faster.

Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.

public static long pow(long x, int y) {
        long result = 1;
        while (y > 0) {
            if ((y & 1) == 0) {
                x *= x;
                y >>>= 1;
            } else {
                result *= x;
                y--;
            }
        }
        return result;
    }
0

Use the below logic to calculate the n power of a.

Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n) Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).

public  int calculatePower1(int a, int b) {
    if (b == 0) {
        return 1;
    }

    int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;

    int temp = 1;
    for (int i = 1; i <= val; i++) {
        temp *= a;
    }

    if (b % 2 == 0) {
        return temp * temp;
    } else {
        return a * temp * temp;
    }
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
  • Thanks, but I am looking for a way which is built into the language and is short. I do know the algorithm to calculate powers. – Hidde Feb 16 '18 at 12:31
0

Apache has ArithmeticUtils.pow(int k, int e).

Noel Yap
  • 18,822
  • 21
  • 92
  • 144
0
import java.util.Scanner;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();

        for (int i = 0; i < t; i++) {

            try {
                long x = sc.nextLong();
                System.out.println(x + " can be fitted in:");
                if (x >= -128 && x <= 127) {
                    System.out.println("* byte");
                }
                if (x >= -32768 && x <= 32767) {
                    //Complete the code
                    System.out.println("* short");
                    System.out.println("* int");
                    System.out.println("* long");
                } else if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
                    System.out.println("* int");
                    System.out.println("* long");
                } else {
                    System.out.println("* long");
                }
            } catch (Exception e) {
                System.out.println(sc.next() + " can't be fitted anywhere.");
            }

        }
    }
}
aboger
  • 2,214
  • 6
  • 33
  • 47
0

int arguments are acceptable when there is a double paramter. So Math.pow(a,b) will work for int arguments. It returns double you just need to cast to int.

int i =  (int) Math.pow(3,10); 
Sandeep Dixit
  • 799
  • 7
  • 12
0

Without using pow function and +ve and -ve pow values.

public class PowFunction {

    public static void main(String[] args) {
        int x = 5;
        int y = -3;
        System.out.println( x + " raised to the power of " + y + " is " + Math.pow(x,y));
        float temp =1;
        if(y>0){
            for(;y>0;y--){
                temp = temp*x;
            }
        } else {
            for(;y<0;y++){
                temp = temp*x;
            }
            temp = 1/temp;
        }
        System.out.println("power value without using pow method.  :: "+temp);
    }
}
Laurel
  • 5,965
  • 14
  • 31
  • 57
-1

Unlike Python (where powers can be calculated by a**b) , JAVA has no such shortcut way of accomplishing the result of the power of two numbers. Java has function named pow in the Math class, which returns a Double value

double pow(double base, double exponent)

But you can also calculate powers of integer using the same function. In the following program I did the same and finally I am converting the result into an integer (typecasting). Follow the example:

import java.util.*;
import java.lang.*; // CONTAINS THE Math library
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n= sc.nextInt(); // Accept integer n
        int m = sc.nextInt(); // Accept integer m
        int ans = (int) Math.pow(n,m); // Calculates n ^ m
        System.out.println(ans); // prints answers
    }
}

Alternatively, The java.math.BigInteger.pow(int exponent) returns a BigInteger whose value is (this^exponent). The exponent is an integer rather than a BigInteger. Example:

import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
      BigInteger bi1, bi2; // create 2 BigInteger objects          
      int exponent = 2; // create and assign value to exponent
      // assign value to bi1
      bi1 = new BigInteger("6");
      // perform pow operation on bi1 using exponent
      bi2 = bi1.pow(exponent);
      String str = "Result is " + bi1 + "^" +exponent+ " = " +bi2;
      // print bi2 value
      System.out.println( str );
   }
}
Pritam Mullick
  • 206
  • 3
  • 13