Java阶乘实例
Java中的阶乘程序:n的阶乘是所有正整数的乘积。 n
的因子由n!
来表示。 例如:
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
这里,4!
发音为“4的阶乘”。阶乘通常用于组合和排列(数学)。
用java语言编写阶乘程序有很多方法。下面来看看在java中编写阶乘程序的两种方法。
- 使用循环实现的阶乘程序
- 使用递归实现的阶乘程序
1. 使用循环实现的阶乘程序
下面来看看在java中使用循环的阶乘程序。
class FactorialExample {
public static void main(String args[]) {
int i, fact = 1;
int number = 5;// It is the number to calculate factorial
for (i = 1; i <= number; i++) {
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
执行上面代码得到以下结果 -
Factorial of 5 is: 120
2. 使用递归实现的阶乘程序
下面来看看在java中使用递归实现阶乘程序。
class FactorialExample2 {
static int factorial(int n) {
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
public static void main(String args[]) {
int i, fact = 1;
int number = 4;// It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of " + number + " is: " + fact);
}
}
执行上面代码得到以下结果 -
Factorial of 4 is: 24
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)