Java Program to Check If a Number is Neon Number or Not

Last Updated : 21 Jan, 2026

A neon number is a number where the sum of the digits of its square is equal to the number itself.

Example:

Input: 9
Square -> 9 * 9 = 81
Sum of digits -> 8 + 1 = 9 -> Neon number

Input: 8
Square -> 8 * 8 = 64
Sum of digits -> 6 + 4 = 10 → Not a Neon number

Algorithm

  • Calculate the square of the number: square = n * n
  • Find the sum of digits of the square using a loop (iterative) or recursion.
  • Compare the sum with the original number:
  • If equal -> Neon number
  • Else -> Not a Neon number

Mathematical Formula:

sum_of_digits(n^2) == n -> Neon number

Approach 1: Iterative Method

Java
class GFG {
    public static boolean checkNeon(int n) {
        int square = n * n; 
        int sum = 0;
        while (square > 0) {
            sum += square % 10; 
            square /= 10;        
        }
        return sum == n;
    }
    public static void main(String[] args) {
        int n = 9;
        if (checkNeon(n))
            System.out.println("Given number " + n + " is a Neon number");
        else
            System.out.println("Given number " + n + " is not a Neon number");
    }
}

Output
Given number 9 is a Neon number

Explanation:

  • square = n * n -> calculate the square of the number (9 * 9 = 81).
  • Loop through the digits of square using % and / -> sum the digits (8 + 1 = 9).
  • Compare the sum with the original number -> sum == n -> if true, number is Neon.
  • checkNeon() returns true for Neon numbers and false otherwise.
  • Time Complexity: O(l), where l = number of digits in square.
  • Auxiliary Space: O(1) (constant space).

Approach 2: Recursive Method

Java
class GFG {
    public static boolean checkNeon(int n) {
        int square = n * n; 
        int sum = 0;
        while (square > 0) {
            sum += square % 10; 
            square /= 10;    
        }
        return sum == n;
    }
    public static void main(String[] args) {
        int n = 9;
        if (checkNeon(n))
            System.out.println("Given number " + n + " is a Neon number");
        else
            System.out.println("Given number " + n + " is not a Neon number");
    }
}

Output
Given number 9 is a Neon number

Explanation:

  • square = n * n -> calculate the square of the number (9 * 9 = 81).
  • Loop through the digits of square using % and / -> sum the digits (8 + 1 = 9).
  • Compare the sum with the original number -> sum == n -> if true, number is Neon.
  • checkNeon() returns true for Neon numbers and false otherwise.
  • Time Complexity: O(log n), proportional to the number of digits in the square.
  • Auxiliary Space: O(log n), due to recursive calls.
Comment