Created
December 31, 2023 12:34
-
-
Save iamgauravbisht/1c4db9326b4ce992b3f2068591229e55 to your computer and use it in GitHub Desktop.
X to the Power n using Recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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