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;
Pritam Mullick Aug 21 '17 at 7:25 2017-08-21 07:25
source share