Dado un número N y una potencia P, la tarea es encontrar el exponente de este número elevado a la potencia dada, es decir, N P . Ejemplos:
Input: N = 5, P = 2 Output: 25 Input: N = 2, P = 5 Output: 32
A continuación se muestran las diversas formas de encontrar N P :
Java
// 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)); } }
Java
// 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)); } }
Java
// 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)); } }
Java
/*java program to calculate of power of given base number */ public class GFG { public static void main(String[] args) { int base = 2; int power = 3; int ans = 1; while (power > 0){ if ((power&1)==1){ // if == 0 there is no point to calculate ans ans = ans * base; } base = base * base; // keep dividing power by 2 using right shift power = power >> 1; } System.out.println(ans); } }