C++ Program to check whether a number is a Strong Number or not

Program to check whether a number is a Strong Number or not

Here we will discuss how to check whether a number is a Strong number or not using C++ Programming language.

Strong Numbers is a number in which the sum of factorial of individual digits of the numbers is equal to the number itself.

To check for Strong Number, break the number into digits, find and add the factorial of each digit and lastly compare the result to the number. If both are equal then the number is a String Number else not a Strong Number.

For Example:145

Sum of factorial of digits of number   = 1! x 4! x 5!

     =  145

Working

Let’s see how the code works:

  • User gives an input.
  • Input is stored in an int type variable say ip.
  • Input is stored in another int type variable, save.
  • A loop is started.
    • In Every loop cycle factorial of last digit of the number will be found.
    • Factorial will be added to an int type variable sum.
    • ip will be divided by 10 i.e. value of ip will be changed.
    • The loop will work until ip is greater than 0.
  • sum will be compared with save
    • If both are equal then the number is a Strong Number
    • Otherwise the number is not a Strong Number.

C++ Code

//C++ program
//Strong Number or not
#include<iostream>
using namespace std;
//main Program
int main()
{
int ip,sum=0;
cout<<"Enter number to check: ";
//user input
cin>>ip;
int save=ip;
//logic to check for Strong Number starts
while(ip)
{
int num=ip%10;
int fact = 1;
//finding factorial of each digit of input
for(int i=num;i>0;i--)
{
fact=fact*i;
}
sum+=fact;
ip/=10;
}
//checking for Strong Nunber
if(sum==save)
{
cout<<save<<" is a Strong Number";
}
else
{
cout<<save<<" is not a Strong Number";
}
//logic ends
return 0;
}

Output

Enter number to check: 145
145 is a Strong Number

Please Login/Signup to comment