计算整数的幂

在 Java 中还有其他计算整数幂的方法吗?

我现在使用的是 Math.pow(a, b),但它返回的是 double,这通常需要做很多工作,而且当您只想使用 int时,它看起来不那么干净(一个幂也总是会导致一个 int)。

有像 Python 中的 a**b那样简单的东西吗?

429184 次浏览

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

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.

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


}

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

Google Guava has math utilities for integers. IntMath

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

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.

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.

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

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

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)

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

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

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


}
}
}

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

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