Writing methods We want to write a method that will enable u
Writing methods We want to write a method that will enable us to calculate a number to a given power. In other words, we are writing a method to mimic what the Math.pow() method we have seen before does. To write this method use the following requirements: The method should return an integer. It should have two parameters x and y both integers. The name of this method will be power(). For the sake of being able to use the method without creating an object, the method must be a static method.
Solution
Hi, Please find my implementation.
public class Power {
public static int power(int x, int y)
{
if( y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
public static void main(String[] args) {
System.out.println(\"Power(3,4): \"+power(3, 4));
}
}
/*
Sample Run:
Power(3,4): 81
*/
