C Program to check Strong Number

CServer Side ProgrammingProgramming

Given a number ‘n’ we have to check whether the number given is Strong Number or not.

Strong number is a number whose sum of all digits’ factorial is equal to the number ‘n’. Factorial implies when we find the product of all the numbers below that number including that number and is denoted by ! (Exclamation sign), For example: 4! = 4x3x2x1 = 24.

So, to find a number whether its strong number, we have to pick every digit of the number like the number is 145 then we have to pick 1, 4 and 5 now we will find factorial of each number i.e, 1! = 1, 4! = 24, 5! = 120.

Now we will sum up 1 + 24 + 120 so we get 145, that is exactly same as the input given, So we can say that the number is strong number.

Example

Input: n = 124
Output: No it is not a strong number
Explanation: 1! + 2! + 4! = 27 which is not equal to n i.e, 124
Input: n = 145
Output: Yes it is a strong number
Explanation: 1! + 4! + 5! = 145

Approach used below is as follows to solve the problem

We will −

• Take each digit starting from the unit place and find its factorial.
• We will add those factorials of each number.
• Compare the result with the original number, If they are equal then, the number is strong number; else the number is not a strong number.

Algorithm

START
In Function int factorial(int r)
Step1 -> Initialize int fact and set as 1
Step2-> Loop while r>1
Set fact as fact * r
Decremnet r by 1
End Loop
Step 3-> Return fact
End Function factorial
In Function int check(int n)
Step 1-> Initialize int temp, rem and result, set result as 0
Step 2-> Set temp as n
Step 3-> Loop while temp
Set rem as temp % 10
Set result as result + factorial(rem)
Set temp as temp/10
End loop
Step 4-> If result == n then,
Return 1
Step 5-> Else
Return 0
End function check
In main(int argc, char const *argv[])
Step 1-> Initialise and set n as 145
Step 2->If check(n) is valid then,
Print "Yes it is a strong number”
Step 3-> Else
Print "no it is not a strong number”
STOP

Example

Live Demo

#include <stdio.h>
int factorial(int r) {
int fact = 1;
while(r>1) {
fact = fact * r;
r--;
}
return fact;
}
int check(int n) {
int temp, rem, result = 0;
temp = n;
while(temp) {
rem = temp % 10;
result = result + factorial(rem);
temp = temp/10;
}
if (result == n)
return 1;
else
return 0;
}
int main(int argc, char const *argv[]) {
int n = 145;
if (check(n))
printf("Yes it is a strong number\n");
else
printf("no it is not a strong number\n");
return 0;
}

If run the above code it will generate the following output −

Yes it is a strong number
Published on 18-Oct-2019 13:23:10
Advertisements