使用遞迴查詢數字階乘的 Java 程式


在本文中,我們將瞭解如何使用遞迴查詢數字的階乘。數字的階乘是它本身與其每個較小數字的乘積。階乘是應用於大於零的自然數的函式。階乘函式的符號是在數字後面加上一個感嘆號,例如:5!

遞迴函式是一個多次呼叫自身的函式,直到滿足特定條件。遞迴是重複以自相似方式的專案的過程。在程式語言中,如果程式允許您在同一個函式內部呼叫一個函式,則稱為該函式的遞迴呼叫。

許多程式語言透過棧來實現遞迴。通常,每當一個函式(呼叫方)呼叫另一個函式(被呼叫方)或自身作為被呼叫方時,呼叫方函式都會將執行控制權轉移到被呼叫方。此轉移過程可能還涉及一些資料從呼叫方傳遞到被呼叫方。

下面是相同內容的演示 -

輸入

假設我們的輸入是 -

Enter the number : 7

輸出

所需的輸出將是 -

The factorial of 7 is 5040

演算法

Step 1 - START
Step 2 - Declare an integer values namely ‘my_input’ and a long value namely ‘my_result’
Step 3 - Read the required values from the user/ define the values
Step 4 - A recursive function ‘factorial’ is defined which takes an integer as input and returns the product of the input and its previous number until the input value is reduced to 1.
Step 5 - The recursive function is called and the value ‘my_input’ is passed to it. Store the return value
Step 6 - Display the result
Step 7 - Stop

示例 1

這裡,輸入是根據提示由使用者輸入的。您可以在我們的編碼練習工具 執行按鈕中即時嘗試此示例。

import java.util.Scanner;
public class Factorial {
   public static void main(String[] args) {
      int my_input ;
      long my_result;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      my_result = factorial(my_input);
      System.out.println("The factorial of " + my_input + " is " + my_result);
   }
   public static long factorial(int my_input){
      if (my_input >= 1)
         return my_input * factorial(my_input - 1);
      else
         return 1;
   }
}

輸出

Required packages have been imported
A reader object has been defined
Enter the number : 7
The factorial of 7 is 5040

示例 2

這裡,整數已預先定義,其值在控制檯上被訪問和顯示。

public class Factorial {
   public static void main(String[] args) {
      int my_input ;
      long my_result;
      my_input = 7;
      System.out.println("The number is defined as " +my_input);
      my_result = factorial(my_input);
      System.out.println("The factorial of " + my_input + " is " + my_result);
   }
   public static long factorial(int my_input){
      if (my_input >= 1)
         return my_input * factorial(my_input - 1);
      else
         return 1;
   }
}

輸出

The number is defined as 7
The factorial of 7 is 5040

更新於: 2022年2月22日

500 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.