java - 将迭代变成递归
问题描述
再会!
我刚刚编写了一个代码作为迭代,它应该总结 0 和 y 之间的偶数。
我现在已经在办公桌上坐了大约两个小时,思考如何在递归中编写相同的代码——到目前为止没有任何进展。我在互联网上找到的唯一解释解释了一个特定更改的简单重复 - 不像我的代码包含两个。("result = result + x;" and "x = x + 2;" ) 有人可以向我解释一下如何将这种迭代转化为递归吗?提前致谢!
public class Sum {
static int method(int y) {
int result = 0;
for (int x = 2; x<=y;)
{
result = result + x;
x = x + 2;
}
return result;
}
public static void main(String[ ] args) {
int result = method(35);
System.out.println("Sum of even numbers between 0-35: " +result);
}
}
解决方案
数字的总和就是这个数字的总和加上这个数字的总和减2。写在代码中:
int method(int y) {
if (y <= 0) {
return 0;
} else {
return y + method(y - 2);
}
}
不用说,这种形式的递归是不必要的,并且会创建StackoverflowException
一个y
非常大的数字。某些语言允许您编写递归函数并指示它是尾递归,以便编译器实际上将其转换为迭代。
推荐阅读
- flutter - 容器尺寸限制仅适用于脚手架
- c# - 按大小升序/降序对文件进行排序
- google-people-api - 将 GoogleContactEntry 的“id”转换为“resourceName”到 Person
- javascript - laravel刀片组件和vue组件有什么区别?
- flutter - 获取 Wordpress 文章并将其放入 Flutter Story 应用程序
- c# - C# 使用泛型、反射和类型推断
- android - 保留所有字符串 JNI android 以防止逆向工程?
- php - 如何获取每天的网站交易 laravel postgres
- python - EarlyStopping TensorFlow 2.0
- python - 我如何从熊猫的“1994”中获得“1994-01-01”?