Saturday, December 17, 2011

Given base and n that are both 1 or more, compute recursively (no loops) the value of base to the n power?

so powerN(3, 2) is 9 (3 squared).





powerN(3, 1) 鈫?3


powerN(3, 2) 鈫?9


powerN(3, 3) 鈫?27








How do I do this. I am very confused. Thanks!


From JavaBat|||int recursive (int base, int power)


{


if(power = = 1)


{


return base;


}


return base*recursive(base, power-1);


}|||The return value of the method is either the base (power equals 1) or the base times the result of calling the method passing the base and the power minus one.





This means that for powers greater than one starting out, you will recursively call the method and subtract one from the power. This recursion continues until the power equals one. At that point, you have a call stack of recursive method calls with no return values yet, and the value of the base is then returned. The previous call then multiplies that return value (base to the power of one) with the base and returns the result (base squared), and so on up the chain until the recursive calls finish in reverse.

No comments:

Post a Comment