In this section, we will learn what is a fascinating number and also create Java programs to check if the given number is fascinating or not. The fascinating number program is frequently asked in Java coding tests.
Fascinating Numbers
Multiplying a number by two and three separately, the number obtained by writing the results obtained with the given number will be called a fascinating number. If the result obtained after concatenation contains all digits from 1 to 9, exactly once.
In other words, we can also say that a number (n) may be a fascinating number if it satisfies the following two conditions:
- If the given number is a 3 or more than three-digit
- If the value getting after concatenation contains all digits from 1 to 9, exactly once.
For example, 192, 1920, 2019, 327, etc. Let's understand the concept of fascinating numbers through an example.
Fascinating Number Example
Let's take any number (n) say 327 and check whether the given number is fascinating or not. On multiplying the given number (n) by 2 and 3, we get:
327×2=654
327×3=981
Now, concatenate the above results to the given number (n).
"327"+"654"+ "981"= 327654981
We observe that the resultant () contains all the digits from 1 to 9, exactly once. Hence, the given number 327 is a fascinating number. Note that, we have not added the result to the given number. Some other fascinating numbers are 192, 219, 273, 327, 1902, 1920, 2019 etc.
Steps to Find Fascinating Numbers
- First, check the given number consist of three digits or not. If no, print cannot be a fascinating number.
- Else, multiply the given number by 2 and 3, separately.
- Convert the results (from step 2) into a string.
- Concatenate the strings (from step 3) with the given number (n).
- Iterate over the string that we get after concatenation and count the frequency of each digit.
- Print "not a fascinating number" if any digit is missing or appeared multiple times. Else, print "fascinating number".
Fascinating Number Java Program
The base condition to check whether a number is fascinating or not is that the number must have at least 3 or more than three digits.
FascinatingNumberExample1.java
Output 1:
Output 2:
Let's create another Java program that finds all the fascinating numbers between the given range.
FascinatingNumberExample2.java
Output: