By SHUBHAM GARG
This article aims to check whether a number is Magic (a number whose sum of digits is evaluated until the sum is found to be 1) or not, implemented in C++.
Hola Coders!
A magic number is a number whose sum of digits is evaluated again and again till the sum of the digits is found to be 1.
The steps to check the number are illustrated below:
1. Recursively, Add the digits of the number till we obtain a single-digit number.
2. Check the obtained single-digit number. If the obtained number is equal to 1 then it's a Magic number.
For example:
Consider the number 4321. After adding the digits, we get the sum as 4+3+2+1 = 10. Then on adding the digits again, we get the sum 1+0 = 1 . Hence, 4321 is a Magic number.
// Program to check if a number is Magic number.
#include
using namespace std;
// Main Function
int main()
{
int n;
cout<<"Enter the Number to Check: ";
cin>>n;
int t=n;
int sum = 0;
while (n > 0 || sum > 9)
{
if (n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
if(sum == 1)
cout<<t<<" is a Magic Number"<<endl;
else
cout<<t<<" is NOT a Magic Number"<<endl;
return 0;
}

Happy Learning!
Submitted by SHUBHAM GARG (Shubham)
Download packets of source code on Coders Packet
Comments