TheAlgorithms-C/math/strong_number.c
Defective Detective 56b72da9fb
chore: move various misc folder... (#1177)
...algorithms to the `math` folder.

Co-authored-by: David Leal <halfpacho@gmail.com>
2022-12-22 11:26:50 -06:00

58 lines
1.1 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @file
* @brief Strong number is a number whose sum of all digits factorial is equal
* to the number n For example: 145 = 1!(1) + 4!(24) + 5!(120)
*/
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
/**
* Check if given number is strong number or not
* @param number
* @return `true` if given number is strong number, otherwise `false`
*/
bool isStrong(int number)
{
if (number < 0)
{
return false;
}
int sum = 0;
int originalNumber = number;
while (originalNumber != 0)
{
int remainder = originalNumber % 10;
int factorial = remainder == 0 ? 0 : 1; /* 0! == 1 */
/* calculate factorial of n */
for (int i = 1; i <= remainder; factorial *= i, i++)
{
;
}
sum += factorial;
originalNumber /= 10;
}
return number == sum;
}
/**
* Test function
* @return void
*/
void test()
{
assert(isStrong(145)); /* 145 = 1! + 4! + 5! */
assert(!isStrong(543)); /* 543 != 5!+ 4! + 3! */
}
/**
* Driver Code
* @return None
*/
int main()
{
test();
return 0;
}