Calculation of the degrees of integers

Is there any other way in Java to calculate the degree of an integer?

I am using Math.pow(a, b) , but it returns a doubling, and that is usually a lot of work, and looks less clean when you just want to use integers (a degree will always also result in an integer)

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

+49
java math
Nov 09 '11 at 20:40
source share
13 answers

Integers are only 32 bits. This means that its maximum value is 2^31 -1 . As you can see, for very small numbers, you quickly get a result that can no longer be represented as an integer. This is why Math.pow uses double.

If you need arbitrary integer precision, use BigInteger.pow . But this, of course, is less effective.

+27
Nov 09 2018-11-11T00:
source share

The best algorithm is based on determining the recursive power 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 } 

The duration of the operation is O (logb). Link: Additional Information

+31
Jan 07 '14 at 23:59
source share

No, there is nothing 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 to integer, produce the result as follows:

 int result = (int)Math.pow(a, b); 
+25
Nov 09 '11 at 20:44
source share

Google Guava has math utilities for integers. Intmath

+6
Aug 30 '14 at
source share

When it is power 2. Keep in mind that you can use the simple and quick shift expression 1 << exponent

example:

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

For larger metrics (over 31) use long

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

By the way. in kotlin you shl instead of << so

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

+5
Dec 19 '17 at 19:22
source share

Well, you can just use Math.pow(a,b) as you used before, and just convert its value using (int) in front of it. Below can be used as an example.

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

where a and b can be double or int values ​​as you wish. It just converts its output to an integer value as needed.

+3
Jul 04 '17 at 13:38 on
source share

Guava math libraries offer two methods that are useful in calculating exact integer degrees:

pow(int b, int k) computes b to kth power and wraps overflow

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

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

If you want to get the result of long , you can simply use the appropriate LongMath methods and pass int arguments.

+2
Jun 02 '16 at 23:48
source share
 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; } } 
+1
Mar 07 '13 at 0:21
source share

I managed to change (borders, even check, negative check of quantity) 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; } } 
+1
Aug 26 '15 at 11:50
source share

Simple (no check for overflow or argument validity) for the re-squaring algorithm to calculate 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 complexity of time is logarithmically exponentially p (i.e. linear with respect to the number of bits needed to represent p).

+1
Jul 18 '17 at 23:08
source share

Unlike Python (where powers can be calculated using ** b), JAVA does not have such a quick way to achieve a power result of two numbers. Java has a function called pow in the Math class that returns a double value

 double pow(double base, double exponent) 

But you can also calculate the degree of an integer using the same function. In the next program, I did the same, and finally I converted the result to 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, java.math.BigInteger.pow(int exponent) returns a BigInteger value whose value (this ^ exponent). The metric is an integer, not 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 ); } } 
0
Aug 21 '17 at 7:25
source share

Use the logic below to calculate the n-degree a.

Usually, if we want to calculate the power n. We multiply "a" by n times. The complexity of this approach will be O (n). Divide the power of n by 2, calculate Exponentattion = multiply "a" only up to n / 2. 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; } } 
0
Feb 15 '18 at 7:34
source share

base is the number you want to include, n is power, we return 1 if n is 0, and we return base if n is 1, if the conditions are not met, we use the formula base * (powerN (base, n-1 )) e.g.: 2 for use with this formula: 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))); } 
0
Aug 02 '18 at 2:10
source share



All Articles