Check if a given number can be represented in given a no. of digits in any base

Given a number and no. of digits to represent the number, find if given number can be represented in given no. of digits in any base from 2 to 32.

```Input: 8 4
Output: Yes
Possible in base 2 as 8 in base 2 is 1000

Input: 8 2
Output: Yes
Possible in base 3 as 8 in base 3 is 22

Input: 8 3
Output: No
Not possible in any base```

We strongly recommend you to minimize your browser and try this yourself first.

The idea is to check all bases one by one starting from base 2 to base 32. How do we check for a given base? Following are simple steps.
1) IF number is smaller than base and digit is 1, then return true.
2) Else if digit is more than 1 and number is more than base, then remove the last digit from num by doing num/base, reduce the number of digits and recur.
3) Else return false

Below is C++ implementation of above idea.

```// C++ program to check if a given number can be
// represented in given number of digits in any base
#include <iostream>
using namespace std;

// Returns true if 'num' can be represented usind 'dig'
// digits in 'base'
bool checkUtil(int num, int dig, int base)
{
// Base case
if (dig==1 && num < base)
return true;

// If there are more than 1 digits left and number
// is more than base, then remove last digit by doing
// num/base, reduce the number of digits and recur
if (dig > 1 && num >= base)
return checkUtil(num/base, --dig, base);

return false;
}

// return true of num can be represented in 'dig'
// digits in any base from 2 to 32
bool check(int num, int dig)
{
// Check for all bases one by one
for (int base=2; base<=32; base++)
if (checkUtil(num, dig, base))
return true;
return false;
}

// Driver program
int main()
{
int num = 8;
int dig = 3;
(check(num, dig))? cout << "Yes" : cout << "No";
return 0;
}
```

Output:

`No`

GATE CS Corner    Company Wise Coding Practice

2 Average Difficulty : 2/5.0
Based on 1 vote(s)