In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through the following topics first in C.
What is Fascinating Number?
A number is said to be a fascinating number if it is (having at least 3 digits) multiplied by 2 and 3, and then both these product’s results are concatenated with the original number, then the new number contains all the digits from 1 to 9 exactly once. There could be any number of zeros and are ignored.
Fascinating number example:
Consider a Number = 192
Then multiply it by two and 3
192 × 2 = 384
192 × 3 = 576
Concatenating the above two numbers with the original number, we get:
“192” + “384” + “576” = 192384576 = result.
Now the final result contains all the digits from 1 to 9. Hence it is a Fascinating Number.
Procedure for Fascinating Number
- First, check if the entered/given number has three digits or not. If not, print “cannot be a Fascinating Number”.
- Else, Multiply the given number with 2 and 3.
- Then convert the product result into a string and Concatenate those strings along with the original number.
- Iterate the string that we get after concatenation and also keep the frequency count of the digits.
- Print “Not a Fascinating Number” if any of the digits (1 to 9) is missing or repeated.
- Else, print “It is a Fascinating Number”.
C Program for 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #include <stdio.h> #include <stdbool.h> #include <math.h> //function int countDigits(int n) { int count = 0; while (n > 0) { count++; n /= 10; } return count; } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); //calculating the product int product2 = num * 2; int product3 = num * 3; //Concatinating all three int concatNum = 0; concatNum += num; concatNum = concatNum* pow(10, countDigits(product2)) + product2; concatNum = concatNum* pow(10, countDigits(product3)) + product3; //Count the occurence int count[10] = { 0 }; while (concatNum > 0) { count[concatNum % 10]++; concatNum = concatNum / 10; } //Check for 1 bool isFound = true; for (int i = 1; i < 10; i++) { if (count[i] != 1) { isFound = false; break; } } //Display the result if (isFound) printf("%d is a Fascinating number.", num); else printf("%d is NOT a Fascinating number.", num); return 0; } |
Output:
Enter a number: 192
192 is a Fascinating number.