Python Program to Find Neon Number
sum(int(d) for d in str(num*num)) == num.Examples
How to Think About It
Algorithm
Code
num = int(input("Enter a number: ")) square = num * num sum_digits = sum(int(d) for d in str(square)) if sum_digits == num: print(f"{num} is a neon number") else: print(f"{num} is not a neon number")
Dry Run
Let's trace the number 9 through the code
Input number
num = 9
Calculate square
square = 9 * 9 = 81
Sum digits of square
digits of 81 are '8' and '1', sum = 8 + 1 = 9
Compare sum with original
sum_digits = 9, num = 9, so they are equal
Print result
"9 is a neon number"
| Step | Value |
|---|---|
| Input number | 9 |
| Square | 81 |
| Sum of digits | 9 |
| Comparison | 9 == 9 (True) |
Why This Works
Step 1: Square the number
We calculate num * num to get the square, which is the base for checking the neon property.
Step 2: Sum digits of the square
By converting the square to a string, we can iterate over each digit and sum them using sum(int(d) for d in str(square)).
Step 3: Compare sum with original number
If the sum of digits equals the original number, it confirms the number is neon; otherwise, it is not.
Alternative Approaches
num = int(input("Enter a number: ")) square = num * num sum_digits = 0 while square > 0: sum_digits += square % 10 square //= 10 if sum_digits == num: print(f"{num} is a neon number") else: print(f"{num} is not a neon number")
def is_neon(num): square = num * num return sum(int(d) for d in str(square)) == num num = int(input("Enter a number: ")) if is_neon(num): print(f"{num} is a neon number") else: print(f"{num} is not a neon number")
Complexity: O(d) time, O(d) space
Time Complexity
The time depends on the number of digits d in the squared number because we sum each digit once.
Space Complexity
Space is used to store the string representation of the square, which is proportional to the number of digits d.
Which Approach is Fastest?
Using arithmetic operations (modulus and division) avoids string conversion and can be faster and use less memory for very large numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String conversion | O(d) | O(d) | Simplicity and readability |
| Arithmetic operations | O(d) | O(1) | Performance with large numbers |
| Function encapsulation | O(d) | O(d) | Code reuse and clarity |