0

Here is the example code, I came across this in Java The Complete reference, 9th edition.

// A simple example of recursion. 

class Factorial {           // this is a recursive method 

int fact(int n) { 

    int result;

    if(n==1) return 1; 

    result = fact(n-1) * n;  //This is my question, why not just (n-1)*n?
    return result;
} } 

class Recursion {
    public static void main(String args[]) { 

    Factorial f = new Factorial();

    System.out.println("Factorial of 3 is " + f.fact(3));  //

} }
TC Ling
  • 29
  • 1
  • 3
    `(n-1) * n` will compute, well, `(n-1) * n`, which is not the factorial of n. – Eran Feb 28 '18 at 10:07
  • 2
    It is calculating value recursively. Calling same function within the function. – pavithraCS Feb 28 '18 at 10:07
  • 1
    Just writting (n-1)*n will execute single time and gives wrong output. We need to have recursive call, so we call same function there – Vipul Feb 28 '18 at 10:08
  • yeah your question is right if you always pass only 3. Try passing 4, now you will understand why need to call `fact(n-1)*n` instead of `(n-1)*n` – Anoop LL Feb 28 '18 at 10:10
  • I suggest you try it and see what the difference is. You can step through the code in your debugger if you are not sure why it makes a difference. – Peter Lawrey Feb 28 '18 at 10:12
  • please refer https://stackoverflow.com/questions/1949454/understanding-basic-recursion – Dhiraj Feb 28 '18 at 10:25

2 Answers2

0

Because otherwise it will not call the function again and will just calculate n*(n-1) and exit. For 3 this will do 3x2=6, which is in fact equal to 3!. However, if you try it with 4!, then your change it will return 4x3=12, when in fact to calculate 4! it should work out 4x3x2x1=24.

PKey
  • 3,715
  • 1
  • 14
  • 39
Jonathan Coustick
  • 1,127
  • 9
  • 19
  • Thanks a lot, Plirkee and everyone else! I realize this after I read the next page and check out the sub topic title. It is indeed recursion! – TC Ling Feb 28 '18 at 10:29
0

Answer is pretty simple, because most factorial algoritms based on recursive method, that means that fucntion calls itself, if write (n -1) * n it will multiply only one time and the result will be wrong(not n!). There are a lot of articles about recursive methods and how factorial works in particularly. Read those for example: https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursive-factorial https://introcs.cs.princeton.edu/java/23recursion/

ibanezn04
  • 478
  • 5
  • 12