gpt4 book ai didi

javascript - 如何打印递归轨迹(阶乘函数)?

转载 作者:行者123 更新时间:2023-11-30 17:37:25 26 4
gpt4 key购买 nike

为了更好地理解递归,我试图找出如何将递归跟踪记录到控制台。我有“追踪”部分,但我不确定如何“冒泡”解决方案。对完美放置的 console.log 语句有什么建议吗?

这是我到目前为止所得到的:

function factorial (num) {
if (num === 1) {
console.log('factorial(' + num + ') = ' + num);
return 1;
} else {
console.log('factorial(' + num + ') = ' + num + ' * ' + 'factorial(' + (num - 1) + ')');
return num * factorial(num - 1);
}
}

将以下内容打印到控制台:

factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1
120

但是 1 * 2 * 3 * 4 * 5 部分呢?我知道它发生在某处,我该如何打印它?

我想我希望它看起来像这样:

1
1 * 2
2 * 3
6 * 4
24 * 5
120

感谢您的任何建议!

好的,经过更多搜索后,我在 CodeRanch 找到了这个,不幸的是没有代码(并且用 Java 编写):

Enter fact(6)  
Enter fact(5)
Enter fact(4)
Enter fact(3)
Enter fact(2)
Enter fact(1)
Enter fact(0)
0!Ret: 1
Ret: 1 * fact(n-1) = 1 * fact(0) = 1 * 1 = 1
Ret: 2 * fact(n-1) = 2 * fact(1) = 2 * 1 = 2
Ret: 3 * fact(n-1) = 3 * fact(2) = 3 * 2 = 6
Ret: 4 * fact(n-1) = 4 * fact(3) = 4 * 6 = 24
Ret: 5 * fact(n-1) = 5 * fact(4) = 5 * 24 = 120
Ret: 6 * fact(n-1) = 6 * fact(5) = 6 * 120 = 720
fact(6) = 720

很酷,对吧?经过更多的实验,我仍然无法实现这一目标......

最佳答案

function factorial (num) {
if (num === 1) {
console.log(num); //print new line after this
return 1;
} else {
var val = factorial(num - 1);
console.log(num +'*' + val); //print new line after this
return num * val;
}
}

关于javascript - 如何打印递归轨迹(阶乘函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21748322/

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