My problem is with this exercise:
Write a recursive method called power that takes a double x, and an integer n and that returns x^n. Hint: a recursive definition of this operation is x^n = x*x^(n-1). Also, remember that anything raised to the zeroeth power is 1. Optional challenge: you can make this method more efficient, when n is even, using x^n=(x^(n/2))^2.
Now call me crazy but I just can't see why recursion is necessary or how it could be implemented into this, here is the code I wrote:
It works, and returns x^n just as the exercise said, but it specified to use a recursive method so if any of you guys could give me a hand in how recursion would work with this problem it would be appreciated.package edu.vtc.aav10260.cis2261; import java.util.Scanner; /** * @author andre * */ public class Power { /** * @param args * @return */ public static double main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Enter the values: "); System.out.print("x= "); double x = kbd.nextDouble(); System.out.print("n= "); int n = kbd.nextInt(); return Math.pow(x, n); } }