user3400493
user3400493

Reputation:

Calculating factorials in Java and printing the steps

The following Java code calculates the factorial of a given number and also prints the intermediate steps.

public class Factorial {
   public static int getFactorial(int number) {
     int n = number;
     int factorial = 1;

     while(n > 1) {
       factorial *= n;
       n--;

       System.out.println(factorial + " * " + n + " = " + factorial);
     }

    return factorial;
   }
}

When the method is called:

Factorial.getFactorial(4);

Should print to the console something like the following:

4 * 3 = 12
12 * 2 = 24
24 * 1 = 24

But instead it prints something like the following:

4 * 3 = 4
12 * 2 = 12
24 * 1 = 24

What am I doing wrong?

Upvotes: 0

Views: 357

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213193

That is happening because you're printing the factorial variable only. Replace:

System.out.println(factorial + " * " + n + " = " + factorial);

with:

System.out.println(factorial + " * " + n + " = " + factorial * n);

Upvotes: 3

Related Questions