Problem: Write a C program to check whether the given number is a Fascinating number or not.

A Fascinating number is a number which when concatenated with its multiple of 2 and 3 together gives a number that contains all digits from 1 to 9 exactly once.

For example: 192.

original number = 192

192 * 2 = 384
192 * 3 = 576

"192"+"384"+"576" = 192384576

//192384576  has all digits from 1 to 9 exactly once

The algorithm to check the Fascinating number in C is as follows:

  1. Input a number.
  2. Compute its multiple of 2 and 3 respectively.
  3. Concatenate the input number, it’s multiple of 2 and 3 together.
  4. Count the occurrence of each digit from 1 to 9 in the resulting number.
  5. If any count is not 1, then the input number is not a Fascinating number otherwise, it is.

Here is the C program which implements the above algorithm to check Fascinating number:

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

//Function to return number of digits in 'n'
int countDigits(int n){
  int count =0;
  while(n>0){
    count++;
    n = n/10;
  }
  return count;
}

int main(void) {
  int num;

  //1. Input a numberint num;
  printf("Enter a number \n");
  scanf("%d",&num);

  //2. Calculate its multiple of 2 and 3 
  int mulOf2 = num*2;
  int mulOf3 = num*3;

  //3. Concatenate num, mulOf2 and mulOf3
  int concatNum = 0;
  concatNum += num;
  concatNum = concatNum*pow(10, countDigits(mulOf2)) + mulOf2;
  concatNum = concatNum*pow(10, countDigits(mulOf3)) + mulOf3;
    
  //4. Count the occurence of each digits.
  int count[10] = {0}; 
  while(concatNum>0){
    count[concatNum%10]++;
    concatNum = concatNum/10;
  }

  //5 Check if any digit count is different than 1
  bool isFasctinating = true;
  for(int i=1; i<10; i++){
    if(count[i] != 1){
      isFasctinating = false;
      break;
    }
  }

  //Print the result
  if(isFasctinating)
    printf("Fascinating Number");
  else
    printf("Non Fascinating Number");

  return 0;
}

Output:

Enter a number
192
Fascinating Number

Enter a number
101
Non Fascinating Number


In the above program, to count the frequency of each digit in the concatenated number, we have uses an array of size 10 i.e. count[10], in which each index represents the digit and its corresponding value as its count.

Note: Digit 0 is not considered while checking Fascinating number.

In this tutorial, we learned What a Fascinating number is and how to check whether the given number is Fascinating or not in the C programming language.

This Post Has 2 Comments

  1. Srikant kadgi

    Send full Program.

    1. Adarsh Kumar

      Program does not work for you?

Leave a Reply

twenty − twenty =