Python Program to Check a Neon Number
Beginner · Numbers
A neon number is a number where the digits of its square add up to the number itself. 9 is a neon number: 9 x 9 = 81, and 8 + 1 = 9.
Program
neon_number.py
num = 9 # or: num = int(input("Enter a number: "))
square = num * num
digit_sum = 0
temp = square
while temp > 0:
digit_sum += temp % 10 # add the last digit
temp //= 10 # then drop it
print(f"Square of {num}: {square}")
print(f"Sum of the digits of {square}: {digit_sum}")
if digit_sum == num:
print(num, "is a neon number")
else:
print(num, "is not a neon number")
Output
Square of 9: 81 Sum of the digits of 81: 9 9 is a neon number
How it works
- The program first squares the number: 9 x 9 = 81.
- The
whileloop adds up the digits of the square, taking the last digit with% 10and dropping it with//= 10. - If that digit sum equals the original number, the number is neon.
- The loop works on
temp, a copy, sosquareis still there to print.
Another way to write it
Searching for neon numbers
Searching for neon numbers
def is_neon(n):
return sum(int(d) for d in str(n * n)) == n
found = [n for n in range(10001) if is_neon(n)]
print("Neon numbers from 0 to 10000:", found)
Output
Neon numbers from 0 to 10000: [0, 1, 9]
Only 0, 1 and 9 are neon numbers: for anything bigger, the digits of the square can never add up to as much as the number.
Try it yourself
Set num = 12 and work out by hand why it is not a neon number.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises