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