From 04e0acc3cf5f83a6aa018575478b4eee54a9c97f Mon Sep 17 00:00:00 2001 From: Divyajyoti Ukirde <30872426+divyajyotiuk@users.noreply.github.com> Date: Mon, 5 Oct 2020 18:22:27 +0530 Subject: [PATCH] feat: added check_factorial (#1155) * feat: added check_factorial * updating DIRECTORY.md * feat: added check_factorial * review changes * review changes Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- DIRECTORY.md | 1 + math/check_factorial.cpp | 64 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 math/check_factorial.cpp diff --git a/DIRECTORY.md b/DIRECTORY.md index 08370c1b2..7e72b439e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -122,6 +122,7 @@ * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/armstrong_number.cpp) * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Check Amicable Pair](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_amicable_pair.cpp) + * [Check Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_factorial.cpp) * [Check Prime](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_prime.cpp) * [Complex Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/complex_numbers.cpp) * [Double Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/double_factorial.cpp) diff --git a/math/check_factorial.cpp b/math/check_factorial.cpp new file mode 100644 index 000000000..2170b81a0 --- /dev/null +++ b/math/check_factorial.cpp @@ -0,0 +1,64 @@ +/** + * @file + * @brief A simple program to check if the given number is a factorial of some + * number or not. + * @author [Divyajyoti Ukirde](https://github.com/divyajyotiuk) + */ +#include +#include + +/** + * Function to check if the given number is factorial of some number or not. + * @param n number to be checked. + * @return if number is a factorial, returns true, else false. + */ + +bool is_factorial(uint64_t n) { + if (n <= 0) { + return false; + } + for (uint32_t i = 1;; i++) { + if (n % i != 0) { + break; + } + n = n / i; + } + if (n == 1) { + return true; + } else { + return false; + } +} + +/** Test function + * @returns void + */ +void tests() { + std::cout << "Test 1:\t n=50\n"; + assert(is_factorial(50) == false); + std::cout << "passed\n"; + + std::cout << "Test 2:\t n=720\n"; + assert(is_factorial(720) == true); + std::cout << "passed\n"; + + std::cout << "Test 3:\t n=0\n"; + assert(is_factorial(0) == false); + std::cout << "passed\n"; + + std::cout << "Test 4:\t n=479001600\n"; + assert(is_factorial(479001600) == true); + std::cout << "passed\n"; + + std::cout << "Test 5:\t n=-24\n"; + assert(is_factorial(-24) == false); + std::cout << "passed\n"; +} + +/** Main function + * @returns 0 on exit + */ +int main() { + tests(); + return 0; +}