# help with recursive method

• September 27th, 2012, 06:27 PM
mflb94
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.
• September 27th, 2012, 06:30 PM
copeg
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: