help with recursive method
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:
Code :
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);
}
}
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.
Re: help with recursive method
Did you not like the advice given to you elsewhere? You should at the very least acknowledge that advice, and ask a question or elaborate if you do not understand.
This thread has been cross posted here:
http://www.java-forums.org/new-java/63329-problem-recursive-method.html
Although cross posting is allowed,
for everyone's benefit, please read:
Java Programming Forums Cross Posting Rules
The Problems With Cross Posting