Equidigital Numbers in C++


Equidigital numbers are mathematically special numbers in which the number of digits in the number is equal to the number in its prime factorization.

In this problem, we are given an integer value n. Our task is to create a program to all equidigital numbers up to n.

Let’s take an example to understand the problem,

Input: n =  12

Output:  1 2 3 5 7 10 11

Solution Approach:

A simple solution to the problem would be finding the factors of the number and check if the number of primes is equal to the number of digits in the number .

The prime factors can be found using sieves method.

Algorithm:

Step 1: find all prime numbers.
Step 2: count the number digits in the number n.

Step 3: Find all prime factors of the number and count the number of digits in it.

Step 4: Compare both the values.
Step 5: Return the number if true. 

Program to illustrate the working of our solution,

Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
const int MAX = 10000;

vector <int> primes;

void findAllPrimes()
{
   bool marked[MAX/2 + 1] = {0};
   for (int i=1; i*i<= (MAX -1)/2; i++)
      for (int j=(i*(i+1))<<1; j<=MAX/2; j=j+2*i+1)
         marked[j] = true;
   primes.push_back(2);
   for (int i=1; i<=MAX/2; i++)
      if (marked[i] == false)
         primes.push_back(2*i + 1);
}

bool isEquidigital(int n) {
   
   if (n == 1)
      return true;
   int number = n;
   int digitSum = 0;
   while (number > 0)
   {
      digitSum++;
      number = number/10;
   }
   int primeDigits = 0 , expCount = 0, p;
   for (int i = 0; primes[i] <= n/2; i++) {
      while (n % primes[i] == 0) {
         p = primes[i];
         n = n/p;
         expCount++;
      }
      while (p > 0) {
         primeDigits++;
         p = p / 10;
      }
      while (expCount > 1) {
         primeDigits++;
         expCount = expCount / 10;
      }
   }
   if (n != 1)
   {
      while (n > 0)
      {
         primeDigits++;
         n = n/10;
      }
   }

   return (primeDigits == digitSum);
}

int main() {

   findAllPrimes();
   int n = 11;
   cout << "Printing Equidigital Numbers less than "<<n<<" : ";
   for (int i=1; i<n; i++)
      if (isEquidigital(i))
         cout<<i<<"\t";
   return 0;
}

Output −

Printing Equidigital Numbers less than 11 : 1 2 3 5 7 10 11

Updated on: 22-Jan-2021

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements