非负整数的阶乘是所有小于或等于n的整数的乘积。例如,阶乘6是6 * 5 * 4 * 3 * 2 * 1,即720。
递归:
// C program to find factorial of given number
#include
// Function to find factorial of given number
unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
// Driver code
int main()
{
int num = 5;
printf("Factorial of %d is %d",
num, factorial(num));
return 0;
}
输出:
Factorial of 5 is 120
迭代式:
#include
// Function to find factorial of given number
unsigned int factorial(unsigned int n)
{
int res = 1, i;
for (i = 2; i <= n; i++)
res *= i;
return res;
}
// Driver code
int main()
{
int num = 5;
printf("Factorial of %d is %d",
num, factorial(num));
return 0;
}
输出:
Factorial of 5 is 120
一线解决方案(使用三元运算符):
// C++ program to find factorial of given number
#include
int factorial(int n)
{
// single line to find factorial
return (n == 1 || n == 0)
? 1
: n * factorial(n - 1);
}
// Driver code
int main()
{
int num = 5;
printf("Factorial of %d is %d",
num, factorial(num));
return 0;
}
// This code is contributed by Rithika palaniswamy.
输出:
Factorial of 5 is 120
使用tgamma()方法:
例子:
Input: n = 4
Output: 24
句法:
tgamma(n+1)=n!
It works upto 20! because c can't store large value
实现:为此使用math.h头文件
#include
#include
int main()
{
// use long long int
// for larger values of n
int n = 4;
// tgamma(n+1)=n!
n = tgamma(n + 1);
printf("%d", n);
return 0;
// This code is contributed by Soumyadip Basak
}
输出:
24
上述解决方案导致大量溢出。请参阅大数阶乘以获取适用于大数的解决方案。
有关更多详细信息,请参阅“程序”中的完整文章以获取更多的数字!
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。