- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a number is magic (Recursive sum of digits is 1) in C++
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
#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
Advertisements