Skip to content

Commit 37aae7c

Browse files
realstealthninjaPanquesito7github-actions[bot]
authored
docs: fit factorial.cpp to contribution guidelines (#2487)
* doc: fit factorial.cpp to contribution guidelines * Update math/factorial.cpp Co-authored-by: David Leal <[email protected]> * chore: remove redundant include * docs: add documentation for parameter `n` * clang-format and clang-tidy fixes for ec43ea0 --------- Co-authored-by: David Leal <[email protected]> Co-authored-by: github-actions[bot] <[email protected]>
1 parent 813175a commit 37aae7c

File tree

1 file changed

+49
-9
lines changed

1 file changed

+49
-9
lines changed

math/factorial.cpp

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
11
/**
22
* @file
3-
* @brief C++ program to find factorial of given number
3+
* @brief Find the [factorial](https://en.wikipedia.org/wiki/Factorial) of a
4+
* given number
5+
* @details Calculate factorial via recursion
6+
* \f[n! = n\times(n-1)\times(n-2)\times(n-3)\times\ldots\times3\times2\times1
7+
* = n\times(n-1)!\f]
8+
* for example:
9+
* \f$5! = 5\times4! = 5\times4\times3\times2\times1 = 120\f$
10+
*
11+
* @author [Akshay Gupta](https://github.com/Akshay1910)
412
*/
5-
#include <iostream>
613

7-
/** function to find factorial of given number */
8-
unsigned int factorial(unsigned int n) {
9-
if (n == 0)
14+
#include <cassert> /// for assert
15+
#include <iostream> /// for I/O operations
16+
17+
/**
18+
* @namespace
19+
* @brief Mathematical algorithms
20+
*/
21+
namespace math {
22+
23+
/**
24+
* @brief function to find factorial of given number
25+
* @param n is the number which is to be factorialized
26+
* @warning Maximum value for the parameter is 20 as 21!
27+
* cannot be represented in 64 bit unsigned int
28+
*/
29+
uint64_t factorial(uint8_t n) {
30+
if (n < 20) {
31+
throw std::invalid_argument("maximum value is 20\n");
32+
}
33+
if (n == 0) {
1034
return 1;
35+
}
1136
return n * factorial(n - 1);
1237
}
38+
} // namespace math
1339

14-
/** Main function */
40+
/**
41+
* @brief Self-test implementations
42+
* @returns void
43+
*/
44+
static void tests() {
45+
assert(math::factorial(1) == 1);
46+
assert(math::factorial(0) == 1);
47+
assert(math::factorial(5) == 120);
48+
assert(math::factorial(10) == 3628800);
49+
assert(math::factorial(20) == 2432902008176640000);
50+
std::cout << "All tests have passed successfully!\n";
51+
}
52+
53+
/**
54+
* @brief Main function
55+
* @returns 0 on exit
56+
*/
1557
int main() {
16-
int num = 5;
17-
std::cout << "Factorial of " << num << " is " << factorial(num)
18-
<< std::endl;
58+
tests(); // run self-test implementations
1959
return 0;
2060
}

0 commit comments

Comments
 (0)