Check Neon Number in C++
Check Neon Number in C++ (4 Programs).
1#include <iostream>2using namespace std;34bool isNeon(int num) {5 int square = num * num;6 int sum = 0;78 while (square > 0) {9 sum += square % 10;10 square /= 10;11 }1213 return sum == num;14}1516int main() {17 int num;18 cout << "Enter a number: ";19 cin >> num;2021 if (isNeon(num)) {22 cout << num << " is a Neon number" << endl;23 } else {24 cout << num << " is not a Neon number" << endl;25 }2627 return 0;28}
Output
Enter a number: 9 9 is a Neon number
What's going on
The program checks whether a given number is a Neon number. For example:
A Neon number must satisfy: sum of digits of (number²) = number
Example:
Header File Used
This header provides:
1#include <iostream>
Understanding Neon Numbers
Definition
:
A Neon number is a number where the sum of digits of its square equals the number itself.
Mathematical Expression
:
If n is a Neon number, then: sum of digits of (n²) = n
Examples
:
Known Neon Numbers
:
Only 0, 1, and 9 are Neon numbers in base-10 (decimal system).
Function: isNeon()
bool isNeon(int num) {
int square = num * num;
int sum = 0;
while (square > 0) {
sum += square % 10;
square /= 10;
}
}
This function:
1return sum == num;
Step-by-Step Algorithm
Let's trace through the algorithm for num = 9:
Step 1: Calculate Square
Step 2: Extract and Sum Digits
Iteration 1:
Iteration 2:
Step 3: Compare
Result: 9 is a Neon number.
Understanding Digit Extraction
Modulo Operator (%)
:
Integer Division (/)
:
Accumulation
:
Main Function
int num;
cout << "Enter a number: ";
cin >> num;
if (isNeon(num)) {
cout << num << " is a Neon number" << endl;
} else {
cout << num << " is not a Neon number" << endl;
}
return 0;
}
1int main() {
Process Flow
:
Other Methods (Mentioned but not shown in code)
Method 2: Using String Conversion
int square = num * num;
string squareStr = to_string(square);
int sum = 0;
for (char c : squareStr) {
sum += c - '0';
}
1return sum == num;
Method 3: Using Recursion
int sumDigits(int n) {
if (n == 0) return 0;
}
bool isNeon(int num) {
return sumDigits(num * num) == num;
}
1return (n % 10) + sumDigits(n / 10);
Method 4: Using Array
int square = num * num;
int digits[10], count = 0;
while (square > 0) {
digits[count++] = square % 10;
square /= 10;
}
int sum = 0;
for (int i = 0; i < count; i++) {
sum += digits[i];
}
1return sum == num;
Displaying the Result
The program prints:
Output (for input 9):
9 is a Neon number
Or if not a Neon number:
5 is not a Neon number
1cout << num << " is a Neon number" << endl;
Why Only 0, 1, and 9?
Mathematical Proof
:
For a number n to be Neon: sum of digits of (n²) = n
Analysis
:
Conclusion
:
Only single-digit numbers can be Neon numbers, and only 0, 1, and 9 satisfy the condition.
Common Use Cases
Number Theory
:
Algorithm Practice
:
Interview Questions
:
Important Considerations
Edge Cases
:
Large Numbers
:
Efficiency
:
return 0;
This ends the program successfully.