Problem: Write a Java program to check whether the given number is a neon number or not.

Example:

Input:  9
Output: Neon Number

Input:  10
Output: Not a Neon Number

A number is said to be a neon number if the sum of digits of its square is equal to itself.

For example: 9.

Neon Number Test

Steps to check neon number in Java:

  1. Input a number.
  2. Find its square.
  3. Compute the sum of digits of the computed square.
  4. Check if the calculated sum is equal to the input number.
  5. If so, then the number is neon otherwise not.

Here is the java program that implements the above steps to check if a number is neon:

import java.util.Scanner;
 
public class Neon {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        int num;
 
        System.out.println("Enter a number");
        num = in.nextInt();
 
        //compute square of 'num' and init sum =0
        int sum =0, sqr = num*num;
 
        //loop through each digits of square
        while(sqr>0){
            sum += sqr%10;   //sum up digit
            sqr = sqr/10;    //remove digit which has been added
        }
 
        if(sum == num)
            System.out.println("Neon Number");
        else
            System.out.println("Not a Neon Number");
    }
}

Output:

Enter a number
9
Neon Number

Print all Neon Numbers in the Given Range

To print all neon numbers, we iterate through all the number in the given range and check each number using the above algorithm whether it is neon number or not.

import java.util.Scanner;
 
public class NeoninRange {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        int low, up, count = 0;
 
        System.out.print("Enter lower range value: ");
        low = in.nextInt();
        System.out.print("Enter upper range value: ");
        up = in.nextInt();
 
        for(int i=low; i<=up; i++){
            if(isNeon(i)) {
                System.out.print(i + ",");
                count++;
            }
        }
 
        if(count == 0)
            System.out.println("No Neon Number in the given range");
    }
 
    private static boolean isNeon(int num){
        int sum =0, sqr = num*num;
 
        while(sqr>0){
            sum += sqr%10;   //sum up digit
            sqr = sqr/10;    //remove digit which has been added
        }
 
        return sum == num;
    }
}

Output:

Enter lower range value: 1
Enter upper range value: 1000
1,9

In this tutorial, we learned to check neon number using the Java programming language.

Leave a Reply

15 − 6 =