Write a java program to check whether the given number is neon number or not.
Example:
1 2 3 4 5 | Input: 9 Output: Neon Number Input: 10 Output: Not a Neon Number |
A Neon number is that number whose sum of digits of its square is equal to the original number. Example 9.
- Take input a number(num).
- Find square (sqr) of the number.
- Compute sum of digits of square (sum).
- If sum == num then its Neon Number else not.
Here is the java implementation of the above-described steps.
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 | 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
1 2 3 | Enter a number 9 Neon Number |
Print all Neon Numbers in the Range
We need to print all Neon number in the given range using java. For this, we will loop through all numbers in the range and will individually check whether it is Neon number or not.
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 | 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.println("Enter lower range value"); low = in.nextInt(); System.out.println("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
1 2 3 4 5 6 | Enter lower range value 1 Enter upper range value 1000 1,9 |
If you have any suggestions or doubts then comment below.