一个数的阶乘的Java程序
非负整数的阶乘,是所有小于或等于 n 的整数的乘积。例如,6 的阶乘是 6*5*4*3*2*1,即 720。
递归:
// Java program to find factorial of given number
class Test
{
// method to find factorial of given number
static int factorial(int n)
{
if (n == 0)
return 1;
return n*factorial(n-1);
}
// Driver method
public static void main(String[] args)
{
int num = 5;
System.out.println("Factorial of "+ num + " is " + factorial(5));
}
}
迭代解决方案:
// Java program to find factorial of given number
class Test
{
// Method to find factorial of given number
static int factorial(int n)
{
int res = 1, i;
for (i=2; i<=n; i++)
res *= i;
return res;
}
// Driver method
public static void main(String[] args)
{
int num = 5;
System.out.println("Factorial of "+ num + " is " + factorial(5));
}
}
一条线解决方案(使用三元运算符):
// Java program to find factorial
// of given number
class Factorial {
int factorial(int n)
{
// single line to find factorial
return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
}
// Driver Code
public static void main(String args[])
{
Factorial obj = new Factorial();
int num = 5;
System.out.println("Factorial of " + num +
" is " + obj.factorial(num));
}
}
// This code is contributed by Anshika Goyal.
上述解决方案会导致小数溢出。请参考大数阶乘以获得适用于大数的解决方案。
有关更多详细信息,请参阅有关数字阶乘的完整文章!