|
1 | 1 | /**
|
2 | 2 | * @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) |
4 | 12 | */
|
5 |
| -#include <iostream> |
6 | 13 |
|
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) { |
10 | 34 | return 1;
|
| 35 | + } |
11 | 36 | return n * factorial(n - 1);
|
12 | 37 | }
|
| 38 | +} // namespace math |
13 | 39 |
|
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 | + */ |
15 | 57 | int main() {
|
16 |
| - int num = 5; |
17 |
| - std::cout << "Factorial of " << num << " is " << factorial(num) |
18 |
| - << std::endl; |
| 58 | + tests(); // run self-test implementations |
19 | 59 | return 0;
|
20 | 60 | }
|
0 commit comments