-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
check_factorial.cpp
74 lines (68 loc) · 1.89 KB
/
check_factorial.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @file
* @brief A simple program to check if the given number is a
* [factorial](https://en.wikipedia.org/wiki/Factorial) of some number or not.
*
* @details A factorial number is the sum of k! where any value of k is a
* positive integer. https://www.mathsisfun.com/numbers/factorial.html
*
* @author [Divyajyoti Ukirde](https://github.com/divyajyotiuk)
* @author [ewd00010](https://github.com/ewd00010)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for cout
/**
* @namespace
* @brief Mathematical algorithms
*/
namespace math {
/**
* @brief Function to check if the given number is factorial of some number or
* not.
* @param n number to be checked.
* @return true if number is a factorial returns true
* @return false if number is not a factorial
*/
bool is_factorial(uint64_t n) {
if (n <= 0) { // factorial numbers are only ever positive Integers
return false;
}
/*!
* this loop is basically a reverse factorial calculation, where instead
* of multiplying we are dividing. We start at i = 2 since i = 1 has
* no impact division wise
*/
int i = 2;
while (n % i == 0) {
n = n / i;
i++;
}
/*!
* if n was the sum of a factorial then it should be divided until it
* becomes 1
*/
return (n == 1);
}
} // namespace math
/**
* @brief Self-test implementations
* @returns void
*/
static void tests() {
assert(math::is_factorial(50) == false);
assert(math::is_factorial(720) == true);
assert(math::is_factorial(0) == false);
assert(math::is_factorial(1) == true);
assert(math::is_factorial(479001600) == true);
assert(math::is_factorial(-24) == false);
std::cout << "All tests have successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
tests(); // run self-test implementations
return 0;
}