Calculating powers of integers

前端 未结 16 2062
情书的邮戳
情书的邮戳 2020-12-08 06:18

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

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 06:50

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

提交回复
热议问题