Hidde
Hidde

Reputation: 11913

Calculating powers of integers

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?

Upvotes: 109

Views: 481561

Answers (18)

Stanislaw Baranski
Stanislaw Baranski

Reputation: 1418

When it's a power of 2 keep in mind that you can use a simple and fast shift expression: 1 << exponent

For 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 <<:

(Java) 1L << 32 = 1L shl 32 (Kotlin)

Upvotes: 72

Laakal
Laakal

Reputation: 687

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

long power (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).

Sample code with tail-recursive optimization:

public class PowerCalculator {
    
    public static void main(String[] args) {
        int base = 7;
        int exponent = 5;
        long result = power(base, exponent);
        System.out.println(base + " ^ " + exponent + " = " + result);
        
    
    }

    public static long power(int a, int b) {
        return powerTailRecursive(a, b, 1);
    }

    private static long powerTailRecursive(int a, int b, long accumulator) {
        if (b == 0) {
            return accumulator;
        } else {
            return powerTailRecursive(a, b - 1, accumulator * a);
        }
    }
}

Reference:More information

Upvotes: 43

Baireddy Naresh
Baireddy Naresh

Reputation: 1

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);
    }
}

Upvotes: 0

Sandeep Dixit
Sandeep Dixit

Reputation: 1036

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); 

Upvotes: 0

sudarshan padale
sudarshan padale

Reputation: 1

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.");
            }

        }
    }
}

Upvotes: 0

Noel Yap
Noel Yap

Reputation: 19758

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

Upvotes: 1

Yerassyl Aben
Yerassyl Aben

Reputation: 21

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;
    }

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691625

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.

Upvotes: 63

mark lamban
mark lamban

Reputation: 49

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;
    }

}

Upvotes: 4

Morriss
Morriss

Reputation: 31

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)));
}

Upvotes: 1

Yuvaraj Ram
Yuvaraj Ram

Reputation: 67

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;
    }
}

Upvotes: 0

Pritam Mullick
Pritam Mullick

Reputation: 226

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 );
   }
}

Upvotes: -1

Michail Alexakis
Michail Alexakis

Reputation: 1585

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).

Upvotes: 2

Shubham Srivastava
Shubham Srivastava

Reputation: 317

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.

Upvotes: 2

BeeOnRope
BeeOnRope

Reputation: 64885

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.

Upvotes: 2

ant
ant

Reputation: 171

Google Guava has math utilities for integers. IntMath

Upvotes: 9

Petar Minchev
Petar Minchev

Reputation: 47363

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);

Upvotes: 38

Smarty77
Smarty77

Reputation: 1348

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;
        }
    }

Upvotes: 1

Related Questions