gpt4 book ai didi

java - 如何使用递归将可视化打印为数字的阶乘

转载 作者:行者123 更新时间:2023-11-30 06:04:09 25 4
gpt4 key购买 nike

我知道如何计算数字的阶乘,但我想显示方法调用自身时内存中发生的情况。所以使用递归的阶乘是如下的

public static long factorial(int n) { 
if (n == 1) return 1;
return n * factorial(n-1);
}

我想实现以下目标

factorial(5) 
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

我已经到了这一点...我在显示方法的递归返回时遇到问题(第二部分)

public static long factorial(int n) {   
System.out.println("factorial("+n+")");
if (n == 1) {
System.out.println("return 1");
return 1;
}
return n * factorial(n-1);
}

最佳答案

返回前尝试打印:

public static long factorial(int n) {   
System.out.println("factorial("+n+")");
if (n <= 1) { // factorial(0) = factorial(1) = 1
System.out.println("return 1");
return 1;
}
long fac = factorial(n-1);
System.out.printf("return %d * %d = %d%n", n, fac, n * fac);
return n * fac;
}

要获取每行的 n 个空格,您可以添加一个辅助函数,该函数接受当前递归的“深度”并相应地打印 n 个空格。

// public function visible to the world
public static long factorial(int n) {
return factorial(5, 0);
}

// helper function that takes in the current depth of
// the recursion
private static long factorial(int n, int depth) {
String spaces = repeat(' ', depth);
System.out.print(spaces);
System.out.println("factorial("+n+")");
if (n <= 1) { // factorial(0) = factorial(1) = 1
System.out.println(spaces + " return 1");
return 1;
}

long fac = factorial(n-1, depth + 1);
System.out.print(spaces);
System.out.printf("return %d * %d = %d%n", n, fac, n * fac);
return n * fac;
}

// helper function to create a String by repeating
// char c, n times.
private static String repeat(char c, int times) {
char[] sequence = new char[times];
Arrays.fill(sequence, c);
return new String(sequence);
}

关于java - 如何使用递归将可视化打印为数字的阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361758/

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