What does the method prod() do in this Java program?

a 夏天 提交于 2019-12-13 02:27:36

问题


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;
    }
}
}

This is an exercise in the book I am stumped on. Why would the program not just recurse until the two numbers are equal and then return n ? Also, where it says,

int result = n * recurse;

How does it multiply int n by recurse which would be (int, int)? How can it multiply one integer by a set of two integers?

In what way am I misunderstanding this program?

EDIT: This is a different question because I am not using factorials


回答1:


prod(x,y) is equivalent to y! when x=1. If x is different from 1, then its doing recursive multiplication (y * (y- 1) * (y -2) .... ) until y = x. Assuming y > x.

By the way, if x > y then prod() will crash.



来源:https://stackoverflow.com/questions/29679144/what-does-the-method-prod-do-in-this-java-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!