📜  Java程序来计算数字的幂

📅  最后修改于: 2021-04-22 00:21:13             🧑  作者: Mango

给定一个数N和一个幂P,任务是找到这个数的指数提高到给定的幂,即N P。

例子:

Input: N = 5, P = 2
Output: 25

Input: N = 2, P = 5
Output: 32

以下是找到N P的各种方法:

  • 方法1:使用递归
    // Java program to find the power of a number
    // using Recursion
      
    class GFG {
      
        // Function to calculate N raised to the power P
        static int power(int N, int P)
        {
            if (P == 0)
                return 1;
            else
                return N * power(N, P - 1);
        }
      
        // Driver code
        public static void main(String[] args)
        {
            int N = 2;
            int P = 3;
      
            System.out.println(power(N, P));
        }
    }
    
    输出:
    8
    
  • 方法2:在循环的帮助下
    // Java program to find the power of a number
    // with the help of loop
      
    class GFG {
      
        // Function to calculate N raised to the power P
        static int power(int N, int P)
        {
            int pow = 1;
            for (int i = 1; i <= P; i++)
                pow *= N;
            return pow;
        }
      
        // Driver code
        public static void main(String[] args)
        {
            int N = 2;
            int P = 3;
      
            System.out.println(power(N, P));
        }
    }
    
    输出:
    8
    
  • 方法3:使用Math.pow()方法
    // Java program to find the power of a number
    // using Math.pow() method
      
    import java.lang.Math;
      
    class GFG {
      
        // Function to calculate N raised to the power P
        static double power(int N, int P)
        {
            return Math.pow(N, P);
        }
      
        // Driver code
        public static void main(String[] args)
        {
            int N = 2;
            int P = 3;
      
            System.out.println(power(N, P));
        }
    }
    
    输出:
    8.0