Java Factorial Calculation Algorithm

  • Hello dear Jetto Developers

    How would you like to learn the factorial calculation algorithm in Java programming language? Here is a guide on how to do it in basic steps:

    First of all, a factorial is the product of all positive integers between a number itself and 1. For example, the factorial of 5 is calculated as follows: 5! = 5 x 4 x 3 x 3 x 2 x 2 x 1 = 120. The algorithm for factorial calculation can be performed recursively or in a loop. In this article, I will explain factorial calculation with recursive.

    Recursive in the most general sense is the iteration of a structure (by itself). In the programming world, if a method calls itself again and again within itself, this method is referred to as a recursive method.

    Now let's start writing the program:

    1. First, we will get a number from the user and assign it to the variable sayi. This will be done in the main method at the beginning of the program.

      Code
      Scanner scanner = new Scanner(System.in);
      System.out.print("Enter the number whose factorial you want to calculate: ");
      int number = scanner.nextInt();
    2. We will then pass the value entered by the user as a parameter to the factorial calculation function and call this function.

      Code
      System.out.println("The factorial of the number you entered: " + factorialCalculate(number));
    3. Now we will prepare our method. Since we will call our method from the main method, we specify it as static and give it the int value because it will return a value.

      Code
      public static int faktoriyelHesapla(int n) { 
      
      }
    4. We add a condition block to return 1 if the entered number is 0.

      Code
      if (n == 0) { 
      	return 1;
      } else {
      
      }
    5. When the entered number is not zero, the else block will be executed. This part is the main logic of the factorial calculation function. If the incoming number is other than 0, the function calls itself again and passes the value (n-1) as a parameter to the factorialCalculate function. This process continues until the value of n is 0 and finally the factorial is obtained and the value is returned.

      Code
      else { 
      	return n * factorialCalculate(n - 1);
      }

      So, we have completed the factorial calculation. You can also calculate it with the loop structure. You can write how you did it in the comments. You can also write your questions.

      Thank you for reading this far.

      All Codes:

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!