Program for the power of the number using recursion in java
Code:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println(power(6,3));
}
public static int power(int n,int pow){
if(pow==1){
return n;
}
return n * power(n,pow-1);
}
}
or
==
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println(power(2,10));
}
public static int power(int n,int pow){
if(pow==1){
return n;
}
if(n==0){
return 0;
}
if(pow%2==0){
return power(n,pow/2) * power(n,pow/2);
}else{
return power(n,pow/2) * power(n,pow/2) * n;
}
}
}
Comments
Post a Comment