In this tutorial you will learn about the Program to check Fascinating Number in Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Fascinating Numbers in Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Fascinating Number?
In Mathematics, any 3-digit number is said to be a fascinating when the base number is multiplied by 2 and 3 respectively and the outcome of the 2 multiplication are concatenated with base number and there is no repeated number in the concatenated number, i.e. from 1 to 9 all are occurred once in the number here. 0 are ignored in the final outcome number. If any number from 1 to 9 is repeated then that number is not a fascinating number
Java Program to check the number is fascinating number
In this program we would find the given number is fascinating number first will take the input from the user and check whether it is a3-digit number or not. If it’s not a 3-digit number then the program will be terminated. Then if the number is a 3-digit number then the program will continue and check the number. The fascinating number is a commonly asked question in coding tests of java.
For example, 192 to be checked
Then
192
192*2=384
192*3=576
“192” + “384” + “576” = 192384576
Here the above number doesn’t repeat any number hence it is a fascinating number.
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 46 47 |
import java.util.*; class Facinating { Public static void main (String[] args) { Scanner sn = new Scanner(System.in); int num,n1,n2,flag,i,f; char ch,d; String s=""; System.out.println("Enter any number of three or more digits "); num=sn.nextInt (); if(num<100) { System.out.println("Invalid Input"); System.exit(0); } n1=num*2; n2=num*3; s=num+""+n1+""+n2; flag=1; for(d='0';d<='9';d++) { f=0; for(i=0;i<s.length();i++) { ch=s.charAt(i); if(d==ch) { f++; } } if(f!=1) { flag=0; break; } } if(flag==1) { System.out.println(num+"facinating number"); } else { System.out.println(num+"is not a facinating number"); } } } |
Output