Skip to content

Instantly share code, notes, and snippets.

@iamgauravbisht
Created December 31, 2023 12:34
Show Gist options
  • Save iamgauravbisht/1c4db9326b4ce992b3f2068591229e55 to your computer and use it in GitHub Desktop.
Save iamgauravbisht/1c4db9326b4ce992b3f2068591229e55 to your computer and use it in GitHub Desktop.
X to the Power n using Recursion
package Recursion;
public class PowerOFX {
// Iterate
public static int itr(int x , int power) {
int result = 1;
for(int i = 1 ; i <= power ; i++ ){
result = result * x;
}
return result;
}
// Recursion
public static int rec(int x, int power) {
if(power == 0) return 1;
if(power == 1) return x;
return x * rec(x,power-1);
}
public static void main(String[] args) {
System.out.println(rec(2,3));
System.out.println(itr(3,3));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment