Java programming Implement the static method power in Power

Java programming
Implement the static method power() in Power java that takes two integer arguments a and b and returns the value of a^b, computed recursively using the recurrence relation a^b = {1 if b 0 aa^b - 1 if b is odd (a^2)^b/2 if b is even $java Power 3 5 243

Solution

Power.java:

public class Power {

   public static void main(String[] args) {
       int a=Integer.parseInt(args[0]);
       int b=Integer.parseInt(args[1]);

       System.out.println(power(a,b));

   }
  
   static int power(int a,int b){
      
       if(b==0) return 1;
       else if(b%2!=0){ //condition where b is odd
           return a*power(a,b-1); //recursive call to Power
       }
       else{ //condition where b is even
           return power(a*a, b/2); // recursive call to Power
       }
   }

}


Sample output:

$java Power 3 5
243

$java Power 2 10
1024

$java Power 10 0
1

Java programming Implement the static method power() in Power java that takes two integer arguments a and b and returns the value of a^b, computed recursively u

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site