Java程式列印給定數字的階乘


給定一個整數型別的數字,編寫一個Java程式來列印它的階乘。正整數n的階乘是n到1的所有值的乘積。例如,3的階乘是(3 * 2 * 1 = 6)。

讓我們用例子來理解問題陳述 -

示例場景1

Input: int n = 4;
Output: res = 24 

計算:4! = 4 * 3 * 2 * 1 = 24

示例場景2

Input: int n = 0;
Output: res = 1

0的階乘始終為1。

使用迭代查詢階乘

在迭代方法中,我們使用迴圈,如forwhile,以遞減順序乘以數字以獲得階乘。

示例

在這個Java程式中,我們使用for迴圈查詢數字的階乘。

public class Example {
    public static void main(String[] args) {
        int num = 6;
		// initial factorial
        int fact = 1; 
        System.out.println("The given number is: " + num);
        // loop to calculate factorial
        for(int i = num; i >= 2; i--) {
            fact = fact * i;
        }
        // printing the result
        System.out.println("The factorial of " + num + " is: " + fact);
    }
}

執行以上程式碼後,將顯示以下輸出 -

The given number is: 6
The factorial of 6 is: 720

使用遞迴查詢階乘

遞迴是一種程式設計實踐,它允許方法根據需要自行呼叫。呼叫自身的函式稱為遞迴函式。在使用遞迴時,有必要提供一個基本情況,該基本情況迫使遞迴函式返回結果或終止函式呼叫。

示例

以下Java程式演示瞭如何在Java中使用遞迴查詢階乘。在這裡,該方法將遞迴呼叫以計算階乘,只要給定的輸入大於或等於1。

public class Example {
   // recursive method to calculate factorial
   public static int factorialCalc(int myInput) {
      // checking if given number is greater than 1 or not
      if (myInput >= 1) {
         // finding the factorial
         return myInput * factorialCalc(myInput - 1);
      } else {
         return 1;
      }
   }
   public static void main(String[] args) {
      int myInput = 7;
      System.out.println("The given number is: " + myInput);
      // calling method to calculate factorial 
      int results = factorialCalc(myInput);
      // printing the result
      System.out.println("The factorial of " + myInput + " is " + results);
   }
}  

執行以上程式碼後,將顯示以下輸出 -

The given number is: 7
The factorial of 7 is 5040

更新於: 2024年9月13日

4K+ 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.