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。
使用迭代法求階乘
在迭代方法中,我們使用迴圈,例如for迴圈或while迴圈,按降序將數字相乘以獲得階乘。
示例
在這個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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP