-4

I'm new to Java and I'm reading a couple of books about it. I can't figure out how the output of this code produced:

import java.util.*;

class myclass {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println(factorial(myScanner.nextInt())+"\n");
    }

    public static int factorial(int n) {
        if (n==0) {
           return 1;
        } else {    
            int recurse = factorial(n-1);
            int result = recurse*n;
            return result;
        }
    }
}

Can anyone please explain this step-by-step for me? I understand the main method and Scanner class, but I don't understand that when I enter an integer like 8 at input, I get 40320 at output.

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
Badboy
  • 151
  • 1
  • 6
  • Please tag the question correctly. Then take a debugger and run the code line by line. – Sami Kuhmonen Apr 24 '16 at 10:29
  • Are you familiar with the [factorial function](https://en.wikipedia.org/wiki/Factorial)? Because 8! is 40320, so that's the expected output. – Michael Apr 24 '16 at 14:53

3 Answers3

0

The function factorial uses recursion to solve the factorial. This means that the function calls itself multiple times, until n becomes 0 (In which it returns 1).

So for n = 3, the program starts by setting the result to

Factorial(3) = factorial(2) * 3,
Factorial(2) = factorial(1) * 2,
Factorial(1) = factorial(0) * 1,
Factorial(0) = 1 (Because of the *if-statement*)

Now you can add the things together, as it knows what Factorial(0), Factorial(1), Factorial(2) and Factorial(3) is.

It then becomes:

Factorial(0) = 1,
Factorial(1) = 1 * 1 = 1,
Factorial(2) = 1 * 2 = 2,
Factorial(3) = 2 * 3 = 6
cenh
  • 154
  • 13
0

First of all: Factorial function

I suppose that you don't understand the recursive factorial function.

Declaration of the function:

public static int factorial(int n){

The factorial of 0 is 1 (the exception):

if(n==0){
    return 1;
}

If the number introduced by the user isn't 0 then:

    else { 
        int recurse = factorial(n-1);
        int result = recurse*n;
        return result;
   }
  1. In this case, for example, call the function with 2. recurse = factorial(2-1), wait until the call to the function ends (in this case calls to the same function, but it isn't a problem, just wait until the function call ends). Therefore call factorial(2-1). To be continued...

  2. factorial(1), n==0 false, therefore get inside else statement. Call factorial(1-1). Another time wait until the function factorial(1-1) ends. To be continued...

  3. factorial(0), n==0true, therefore return 1. The call to the functions ended, now we will continue the step 2.

  4. Continue factorial(1) in step 2: The factorial(1-1) returns 1 and store it in recurse.int result = recurse * n so result = 1·1. Finally in this step return result (1). Now we go to step 1 that is still waiting in the factorial(1) call.

  5. Continues factorial(2) in step 1: The factorial(2-1) returns 1 ans store it in recurse. int result = recurse * n so result = 1·2. And return result (2).

Finally the factorial(2) returns 2. Think about factorial(3), 4, 5, 6, 7, and finally you will understand factorial 8. The most important thing is that, when you call the same function where you are, it save the state in a stack and wait until it finish.

Jose J
  • 24
  • 5
0

Code is easier to work through when you format it properly, so please do that in the future. Sometimes code is also easier to work through when you make it more concise. Notice that you can "inline" the result variable:

public static int factorial(int n) {

    if (n == 0) {
        return 1; 
    }
    else {
        int recurse = factorial(n - 1);
        return recurse * n;
    }
}

Or more simply:

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

Now let's try some values. Let's try with the value of "0":

public static int factorial(int n) {
    if (n == 0) { 
        return 1; //<-- Returns 1
    }
    return n * factorial(n-1);
}

Ok, that's right: 0! = 1.

Let's try with the value of "1":

public static int factorial(int n) {
    if (n == 0) { 
        return 1; //not reached
    }
    return n * factorial(n-1); //<-- 1 * factorial(0) = 1 * 1 = 1
}

Good: 1! = 1.

Let's try with the value of "8":

public static int factorial(int n) {
    if (n == 0) { 
        return 1; //not reached
    }
    return n * factorial(n-1); //<-- 8 * factorial(8-1) = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 40320
}

This makes sense since 8! = 40,320.

The way this is done is called recursion since the method is essentially calling itself. When done well, recursion is a beautiful part of programming since the code is typically fairly concise and is one of a "divide and conquer" mentality. This is an introductory concept in programming.

A good programmer will always be thinking about the system of values. So in this case, your function will provide a StackOverFlow error if n is -1, for example. (You can change the code to read if (n <= 1)).

Community
  • 1
  • 1
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80