Find Factorial of a Number Using Recursion in Java

Exercise:

Write a Java Program to find factorial of a number using recursion.

Click Here to View the Solution!
public class FactorialCalculator {
  
     public static void main(String[] args) {
         int number = 8;
         long factorial = multiplyNumbers(number);
         System.out.println("Factorial of " + number + " = " + factorial);
     }
     public static long multiplyNumbers(int number)
     {
         if (number >= 1)
             return number * multiplyNumbers(number - 1);
         else
             return 1;
     }
 } 
Click Here to View the Output!
Factorial of 8 = 40320
Click Here to View the Explanation!
  • This program calculates factorial of a number by employing Recursive Method, which divides the problem into sub-units and then integrates the results at the end.
  • A Negative number does not possess any factorial, whereas the factorial value for ‘0’ equals ‘1’.
  • The method for calibrating the factorial for a number namely ‘n’, having a positive value, is to take product of that number with the value one less than the current number and continue this process until the last number to be taken product with is ‘1’.
  • Primarily, number ‘8’ is passed to the parameter of multiplyNumbers() function.
  • Complying with the conditions of recursive function, ‘8’ poses to be greater than ‘1’; therefore it is taken product with the resultant factorial values of the function. This time the value of the number decreases by ‘1’ i.e. ‘7’. As ‘7’ is still greater than ‘1’ therefore the function will be called again, passing ‘5’ as an argument. 8 * multiplyNumbers(8-1) = 8 * multiplyNumbers(7)
  • This process will continue, as long as the value of the number does not approach less than ‘1’.
  • The function will stop calling itself, once the value of number tends to be less than ‘1’.
  • As mentioned above, the factorial value of ‘0’ is ‘1’, hence after calibrating products for the given number ‘8’, the function returns a factorial value ‘40320’.

%d bloggers like this: