In this tutorial, we will write two programs for the Neon number in Java.
- Program to check whether the nuber neon number or not in Java
- Display all the neon numbers within the specified range in java.
Neon Numbers
A number is said to be a neon number if the sum of the digits of a square of the number is equal t the original number.
Example: 9 is a Neon number (see explanation in the diagram).
Procedure to Find Neon Number
- Read an integer (n), user input.
- Find the square of that number and store it in a variable.
- After that, sum each of the digits of the squared number and again store it in some variable.
- Lastly, compare the sum number with the original number (n). If both are equal then the given number is a neon number, else it is not a neon number.
Java Program to Check given number is Neon number or not
Based on the above procedure, let us apply it in a java program to check for neon numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.*; public class NeonNumberExample1 { public static void main(String args[]) { int sum = 0, num; Scanner sc = new Scanner(System.in); System.out.print("Enter the Number: "); num = sc.nextInt(); //square of a number int square = num * num; while (square != 0) { int digit = square % 10; sum = sum + digit; square = square / 10; } //compare and display if (num == sum) System.out.println(num + " is a Neon Number."); else System.out.println(num + " is not a Neon Number."); } } |
Output:
Enter the Number: 9
9 is a Neon Number.
//Another Execution
Enter the Number: 45
45 is not a Neon Number.
Java Program to find Neon numbers between a specified range
The following java program finds all the neon numbers present in the specified range. The range will be specified by the user during runtime. Using loops the program will find all the Neon numbers within that range.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import java.util.Scanner; public class NeonNumber { public static boolean isNeon(int num) { int sum = 0; int square = num * num; while(square != 0) { sum += square % 10; square /= 10; } return (sum == num); } public static void main(String[] args) { int lrRange = 0, upRange = 0; Scanner scan = new Scanner(System.in); //user inputs for max and min value System.out.print("Enter lower range: "); lrRange = scan.nextInt(); System.out.print("Enter the upper range: "); upRange = scan.nextInt(); // check number System.out.println("\nAll the Neon numbers between "+lrRange+" to "+ upRange+" are: "); for(int i=lrRange; i<=upRange; i++) { //calling function by passing i if(isNeon(i)) System.out.print(i+" "); } scan.close(); } } |
Output:
Enter lower range: 0
Enter the upper range: 10000
All the Neon numbers between 0 to 10000 are:
0 1 9