gpt4 book ai didi

java - 将递归方法转化为公式

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:10:37 25 4
gpt4 key购买 nike

这个查询对你们来说可能很简单,但我真的不知道为什么我在过去 2 小时里抓耳挠腮。

下面是简单的代码,通过相同的方法循环 99 次,结果将是 5050。

class test {
public static void main(String args[]) {
test test1 = new test();
System.out.println(test1.xyz(100));
}
public int xyz(int num) {
if(num ==1) {
return 1;
}
else {
return(xyz(num-1) + num);
}
}
}

我的问题是如何手动解决这段代码。我需要使用什么方程式?

最佳答案

递归函数 xyz() 中发生的事情是将 100 加到 1

100 + 99 + 98 + .... + 1

表示对第第n个自然数求和!所以你可以使用一个简单的 formula查找结果:

n(n + 1) / 2

在程序中:

n = input;
sum = n(n + 1) / 2

或者,如果你想循环求和,你可以这样做:

sum = 0;
for (i = 1; i <= input; i++)
sum += i; // sum = sum + i

关于java - 将递归方法转化为公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31309645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com