# Check if a number is magic (Recursive sum of digits is 1) in C++

C++Server Side ProgrammingProgramming

Here we will see one program, that can check whether a number is magic number or not. A number is said to be magic number, when the recursive sum of the digits is 1. Suppose a number is like 50311 = 5 + 0 + 3 + 1 + 1 = 10 = 1 + 0 = 1, this is magic number.

To check whether a number is magic or not, we have to add the digits until a single-digit number is reached.

## Example

Live Demo

#include <iostream>
using namespace std;
int isMagicNumber(int n) {
int digit_sum = 0;
while (n > 0 || digit_sum > 9) {
if (n == 0) {
n = digit_sum;
digit_sum = 0;
}
digit_sum += n % 10;
n /= 10;
}
return (digit_sum == 1);
}
int main() {
int number = 50311;
if(isMagicNumber(number)){
cout << number << " is magic number";
} else {
cout << number << " is not magic number";
}
}

## Output

50311 is magic number
Published on 21-Oct-2019 08:45:41