WPILibC++ 2024.3.2
factorial.hpp
Go to the documentation of this file.
1/*################################################################################
2 ##
3 ## Copyright (C) 2016-2023 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 gcem
29{
30
31namespace internal
32{
33
34// T should be int, long int, unsigned int, etc.
35
36template<typename T>
37constexpr
38T
40noexcept
41{ // table for x! when x = {2,...,16}
42 return( x == T(2) ? T(2) : x == T(3) ? T(6) :
43 x == T(4) ? T(24) : x == T(5) ? T(120) :
44 x == T(6) ? T(720) : x == T(7) ? T(5040) :
45 x == T(8) ? T(40320) : x == T(9) ? T(362880) :
46 //
47 x == T(10) ? T(3628800) :
48 x == T(11) ? T(39916800) :
49 x == T(12) ? T(479001600) :
50 x == T(13) ? T(6227020800) :
51 x == T(14) ? T(87178291200) :
52 x == T(15) ? T(1307674368000) :
53 T(20922789888000) );
54}
55
56template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
57constexpr
58T
60noexcept
61{
62 return( x == T(0) ? T(1) :
63 x == T(1) ? x :
64 //
65 x < T(17) ? \
66 // if
68 // else
69 x*factorial_recur(x-1) );
70}
71
72template<typename T, typename std::enable_if<!std::is_integral<T>::value>::type* = nullptr>
73constexpr
74T
75factorial_recur(const T x)
76noexcept
77{
78 return tgamma(x + 1);
79}
80
81}
82
83/**
84 * Compile-time factorial function
85 *
86 * @param x a real-valued input.
87 * @return Computes the factorial value \f$ x! \f$.
88 * When \c x is an integral type (\c int, <tt>long int</tt>, etc.), a simple recursion method is used, along with table values.
89 * When \c x is real-valued, <tt>factorial(x) = tgamma(x+1)</tt>.
90 */
91
92template<typename T>
93constexpr
94T
95factorial(const T x)
96noexcept
97{
99}
100
101}
102
103#endif
type
Definition: core.h:556
constexpr T factorial_recur(const T x) noexcept
Definition: factorial.hpp:59
constexpr T factorial_table(const T x) noexcept
Definition: factorial.hpp:39
Definition: is_even.hpp:29
constexpr T factorial(const T x) noexcept
Compile-time factorial function.
Definition: factorial.hpp:95
constexpr return_t< T > tgamma(const T x) noexcept
Compile-time gamma function.
Definition: tgamma.hpp:80