TheAlgorithms-C/math/strong_number.c

58 lines
1.1 KiB
C
Raw Normal View History

2017-07-13 03:09:15 +03:00
/**
2020-08-11 18:01:10 +03:00
* @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)
2017-07-13 03:09:15 +03:00
*/
2020-08-11 18:01:10 +03:00
#include <assert.h>
#include <stdbool.h>
2020-04-08 16:41:12 +03:00
#include <stdio.h>
2017-07-13 03:09:15 +03:00
2020-08-11 18:01:10 +03:00
/**
* 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)
{
2020-08-11 18:01:10 +03:00
if (number < 0)
{
return false;
}
int sum = 0;
2020-08-11 18:01:10 +03:00
int originalNumber = number;
while (originalNumber != 0)
{
2020-08-11 18:01:10 +03:00
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++)
{
2020-08-11 18:01:10 +03:00
;
}
2020-08-11 18:01:10 +03:00
sum += factorial;
originalNumber /= 10;
}
2020-08-11 18:01:10 +03:00
return number == sum;
}
/**
* Test function
* @return void
*/
void test()
{
assert(isStrong(145)); /* 145 = 1! + 4! + 5! */
assert(!isStrong(543)); /* 543 != 5!+ 4! + 3! */
}
2020-08-11 18:01:10 +03:00
/**
* Driver Code
* @return None
*/
2020-04-08 16:41:12 +03:00
int main()
{
2020-08-11 18:01:10 +03:00
test();
return 0;
}