Программа на Java для вычисления степени числа

Опубликовано: 12 Января, 2022

Учитывая число N и степень P, задача состоит в том, чтобы найти показатель степени этого числа в заданной степени, то есть N P.

Примеры:

Ввод: N = 5, P = 2
Выход: 25

Ввод: N = 2, P = 5.
Выход: 32

Below are the various ways to find NP:

  • Method 1: Using Recursion
    // 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));
        }
    }
    Output:
    8
    
  • Method 2: With the help of Loop
    // 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));
        }
    }
    Output:

    8
    
  • Method 3: Using Math.pow() method
    // 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));
        }
    }
    Output:
    8.0
    

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.