First of all, this is not schoolwork - just my curiousity as I for some reason can't get my head around it and solve it. I come up with these stupid things all the time and it annoys the hell out of me when I cant solve them.
Code example is in C# but solution doesn't have to be in any particular programming-language.
long powerofnum(short num, long powerof)
{
return powerofnum2(num, powerof, powerof);
}
long powerofnum2(short num, long powerof, long holder)
{
if (num == 1)
return powerof;
else
{
return powerof = powerofnum2(num - 1, holder * powerof,开发者_JAVA百科 holder);
}
}
As you can see I have two methods. I call for powerofnum(value, powerofvalue) which then calls the next method with the powerofvalue also in a third parameter as a placeholder so it remembers the original powerof value through the recursion.
What I want to accomplish is to do this with only one method. I know I could just declare a variable in the first method with the powerof value to remember it and then iterate from 0 to value of num. But as this is a theoretical question I want it done recursively.
I could also in the first method just take a third parameter called whatever to store the value just like I do in the second method that is called by the first, but that looks really stupid. Why should you have to write what seems like the same parameter twice?
Rules explained in short:
- no iteration
- scope-specific variables only
- only one method
Anyhow, I'd appreciate a clean solution.
Good luck :)
Pseudocode:
// power(x, y) == x^y, only works for positive integer y
function power(x, y) {
return y <= 1 ? x : x * power(x, y - 1);
}
精彩评论