Skip to content

Commit

Permalink
minor refactor to factorial and update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kthohr committed Aug 26, 2023
1 parent 8c2d4b4 commit 345cf52
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
32 changes: 17 additions & 15 deletions include/gcem_incl/factorial.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,24 @@ constexpr
T
factorial_table(const T x)
noexcept
{ // table for x! when x = {2,...,16}
return( x == T(2) ? T(2) : x == T(3) ? T(6) :
{ // table for x! when x = {0, ..., 20}
return( x == T(0) ? T(1) : x == T(1) ? T(1) :
x == T(2) ? T(2) : x == T(3) ? T(6) :
x == T(4) ? T(24) : x == T(5) ? T(120) :
x == T(6) ? T(720) : x == T(7) ? T(5040) :
x == T(8) ? T(40320) : x == T(9) ? T(362880) :
//
x == T(10) ? T(3628800) :
x == T(11) ? T(39916800) :
x == T(12) ? T(479001600) :
x == T(13) ? T(6227020800) :
x == T(14) ? T(87178291200) :
x == T(15) ? T(1307674368000) :
T(20922789888000) );
x == T(10) ? T(3628800) :
x == T(11) ? T(39916800) :
x == T(12) ? T(479001600) :
x == T(13) ? T(6227020800) :
x == T(14) ? T(87178291200) :
x == T(15) ? T(1307674368000) :
x == T(16) ? T(20922789888000) :
x == T(17) ? T(355687428096000) :
x == T(18) ? T(6402373705728000) :
x == T(19) ? T(121645100408832000) :
T(2432902008176640000) );
}

template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
Expand All @@ -56,14 +61,11 @@ T
factorial_recur(const T x)
noexcept
{
return( x == T(0) ? T(1) :
x == T(1) ? x :
//
x < T(17) ? \
return( x < T(21) ? \
// if
factorial_table(x) :
// else
x*factorial_recur(x-1) );
// else (but overflow is almost guaranteed here)
x * factorial_recur(x - 1) );
}

template<typename T, typename std::enable_if<!std::is_integral<T>::value>::type* = nullptr>
Expand Down
2 changes: 2 additions & 0 deletions tests/factorial.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ int main()
#ifndef _WIN32
GCEM_TEST_COMPARE_VALS(gcem::factorial,std_fn, 13L);
GCEM_TEST_COMPARE_VALS(gcem::factorial,std_fn, 16L);
GCEM_TEST_COMPARE_VALS(gcem::factorial,std_fn, 18L);
GCEM_TEST_COMPARE_VALS(gcem::factorial,std_fn, 20L);
#endif

//
Expand Down

0 comments on commit 345cf52

Please sign in to comment.