WPILibC++ 2023.4.3-108-ge5452e3
factorial.hpp
Go to the documentation of this file.
1/*################################################################################
2 ##
3 ## Copyright (C) 2016-2022 Keith O'Hara
4 ##
5 ## This file is part of the GCE-Math C++ library.
6 ##
7 ## Licensed under the Apache License, Version 2.0 (the "License");
8 ## you may not use this file except in compliance with the License.
9 ## You may obtain a copy of the License at
10 ##
11 ## http://www.apache.org/licenses/LICENSE-2.0
12 ##
13 ## Unless required by applicable law or agreed to in writing, software
14 ## distributed under the License is distributed on an "AS IS" BASIS,
15 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 ## See the License for the specific language governing permissions and
17 ## limitations under the License.
18 ##
19 ################################################################################*/
20
21/*
22 * compile-time factorial function
23 */
24
25#ifndef _gcem_factorial_HPP
26#define _gcem_factorial_HPP
27
28namespace internal
29{
30
31// T should be int, long int, unsigned int, etc.
32
33template<typename T>
34constexpr
35T
37noexcept
38{ // table for x! when x = {2,...,16}
39 return( x == T(2) ? T(2) : x == T(3) ? T(6) :
40 x == T(4) ? T(24) : x == T(5) ? T(120) :
41 x == T(6) ? T(720) : x == T(7) ? T(5040) :
42 x == T(8) ? T(40320) : x == T(9) ? T(362880) :
43 //
44 x == T(10) ? T(3628800) :
45 x == T(11) ? T(39916800) :
46 x == T(12) ? T(479001600) :
47 x == T(13) ? T(6227020800) :
48 x == T(14) ? T(87178291200) :
49 x == T(15) ? T(1307674368000) :
50 T(20922789888000) );
51}
52
53template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
54constexpr
55T
57noexcept
58{
59 return( x == T(0) ? T(1) :
60 x == T(1) ? x :
61 //
62 x < T(17) ? \
63 // if
65 // else
66 x*factorial_recur(x-1) );
67}
68
69template<typename T, typename std::enable_if<!std::is_integral<T>::value>::type* = nullptr>
70constexpr
71T
72factorial_recur(const T x)
73noexcept
74{
75 return tgamma(x + 1);
76}
77
78}
79
80/**
81 * Compile-time factorial function
82 *
83 * @param x a real-valued input.
84 * @return Computes the factorial value \f$ x! \f$.
85 * When \c x is an integral type (\c int, <tt>long int</tt>, etc.), a simple recursion method is used, along with table values.
86 * When \c x is real-valued, <tt>factorial(x) = tgamma(x+1)</tt>.
87 */
88
89template<typename T>
90constexpr
91T
92factorial(const T x)
93noexcept
94{
96}
97
98#endif
type
Definition: core.h:575
constexpr T factorial(const T x) noexcept
Compile-time factorial function.
Definition: factorial.hpp:92
Definition: Eigen_Colamd.h:50
constexpr T factorial_recur(const T x) noexcept
Definition: factorial.hpp:56
constexpr T factorial_table(const T x) noexcept
Definition: factorial.hpp:36
constexpr return_t< T > tgamma(const T x) noexcept
Compile-time gamma function.
Definition: tgamma.hpp:74