1.含义
阶乘(factorial)的定义是:
0! = 1
n! = n * (n - 1) !
展开之后的数列为:
- 0!=1
- 1!=11!=1
- 2!=2×1=22!=2×1=2
- 3!=3×2×1=63!=3×2×1=6
- 4!=4×3×2×1=244!=4×3×2×1=24
- 5!=5×4×3×2×1=1205!=5×4×3×2×1=120
- 以此类推...
以下是三种阶乘factorial的三种代码实现方式。为了简化问题,假设输入的n都是正数。
2.常规方式
递归的方式实现阶乘计算,优点是代码简单直观。
#include <iostream>
int factorial(int n)
{
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main()
{
int n = factorial(10);
std::cout << n <<std::endl;
}
3.模板元编程
编译期的编程,最重要的是把计算转换为类型推导。
先定义模板,再特化。代码基本上就是数学定义的简单映射了。
#include <iostream>
template <int n>
struct factorial {
static const int value =
n * factorial<n - 1>::value;
};
template <>
struct factorial<0> {
static const int value = 1;
};
int main()
{
std::cout << factorial<10>::value <<std::endl;
}
4.constexpr 编译期求值
constexpr 的语义是“常量表达式”,也就是在编译期可求值的表达式。
constexpr所修饰的变量一定是编译期可求值的。
constexpr修饰函数,至少对一组实参,可以在编译期间产生编译期常数。
#include <iostream>
constexpr int factorial(int n)
{
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main()
{
constexpr int n = factorial(10);
std::cout << n <<std::endl;
}