递归函数幂,看看你能不能解决
首先,这不是作业——只是我的好奇心,因为出于某种原因我无法集中注意力并解决它。我总是想出这些愚蠢的事情,当我无法解决它们时,我会非常恼火。
代码示例采用 C# 语言,但解决方案不必采用任何特定的编程语言。
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, holder);
}
}
正如你所看到的,我有两种方法。我调用 powerofnum(value, powerofvalue) ,然后它调用下一个方法,其中 powerofvalue 也在第三个参数中作为占位符,以便它通过递归记住原始 powerof 值。
我想要完成的是仅用一种方法来完成此任务。 我知道我可以在第一个方法中使用 powerof value 声明一个变量来记住它,然后从 0 迭代到 num 的值。但由于这是一个理论问题,我希望它递归地完成。
我也可以在第一个方法中只采用第三个参数,称为“whatever”来存储值,就像我在第一个方法调用的第二个方法中所做的那样,但这看起来非常愚蠢。为什么你必须将看似相同的参数写两次?
简而言之:
- 没有迭代
- 范围特定的变量只有
- 一种方法
无论如何,我希望有一个干净的解决方案。
祝你好运 :)
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, 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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
伪代码:
Pseudocode: