1
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

Mekap
  • 2,065
  • 14
  • 26
Walter Straub
  • 83
  • 1
  • 1
  • 8
  • Have you tried going through what happens with a debugger or pen and paper? – Zavior Apr 16 '15 at 15:22
  • prod(int, int) returns an integer -- so n * recurse is just multiplying two integers. You should try stepping through the program in a debugger (or alternatively, add sysouts) to see what's happening here. – Dave Apr 16 '15 at 15:22
  • possible duplicate of [Factorial using Recursion in Java](http://stackoverflow.com/questions/8183426/factorial-using-recursion-in-java) – durron597 Apr 16 '15 at 15:22
  • 2
    @durron597 This isn't actually factorial. – Bubletan Apr 16 '15 at 15:23
  • 1
    Also, `recurse` is not a set of two integers , it is single int value returned by `prod` method ( which is either n for base case or result) after unwinding each recursion – Ravi Yenugu Apr 16 '15 at 15:39

1 Answers1

2

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.

Mekap
  • 2,065
  • 14
  • 26
  • You could write `y*(y-1)*(y-2)*...*(x+1)*x` or `y!/(x-1)!` as a little more definite looking expressions for the "unrolled" product. – Lutz Lehmann Apr 16 '15 at 16:50