public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
这是我被难住的书中的一个练习。为什么程序不只是递归直到两个数字相等然后返回 n ?另外,它说,
int result = n * recurse;
它如何将 int n
乘以递归,即 (int, int)
?如何将一个整数乘以一组两个整数?
我在什么方面误解了这个程序?
编辑:这是一个不同的问题,因为我没有使用阶乘
最佳答案
当 x=1
时,
prod(x,y)
相当于 y!
。
如果 x
与 1
不同,则执行递归乘法 (y * (y- 1) * (y -2) .... )
直到y = x
。
假设 y > x
。
顺便说一下,如果 x > y
则 prod()
将会崩溃。
关于java - 这个 Java 程序中 prod() 方法做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29679144/