Check if a given number can be represented in given a no. of digits in any base
Last Updated :
27 Feb, 2023
Given a number and no. of digits to represent the number, find if the given number can be represented in given no. of digits in any base from 2 to 32.
Examples :
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 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 the number is smaller than the base and the digit is 1, then return true.
2) Else if the digit is more than 1 and the 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 the implementation of the above idea.
C++
// 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 using '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;
}
Java
// Java program to check if a
// given number can be represented
// in given number of digits in any base
import java.io.*;
public class GFG
{
// Returns true if 'num' can be
// represented using 'dig' digits in 'base'
static boolean 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
static boolean 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 code
public static void main (String[] args)
{
int num = 8;
int dig = 3;
if(check(num, dig))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to check
# if a given number can be
# represented in given number
# of digits in any base
# Returns true if 'num' can
# be represented using 'dig'
# digits in 'base'
def checkUtil(num,dig,base):
# Base case
if (dig==1 and 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 and 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
def check(num,dig):
# Check for all bases one by one
for base in range(2,33):
if (checkUtil(num, dig, base)):
return True
return False
# driver code
num = 8
dig = 3
if(check(num, dig)==True):
print("Yes")
else:
print("No")
# This code is contributed
# by Anant Agarwal.
C#
// C# program to check if a given
// number can be represented in
// given number of digits in any base
using System;
class GFG {
// Returns true if 'num' can be
// represented using 'dig' digits
// in 'base'
static bool checkUtil(int num, int dig,
int i)
{
// Base case
if (dig == 1 && num < i)
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 >= i)
return checkUtil((num / i), --dig, i);
return false;
}
// return true of num can be
// represented in 'dig' digits
// in any base from 2 to 32
static bool check(int num, int dig)
{
// Check for all bases one by one
for (int i = 2; i <= 32; i++)
if (checkUtil(num, dig, i))
return true;
return false;
}
// Driver code
public static void Main()
{
int num = 8;
int dig = 3;
if(check(num, dig))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to check if a given
// number can be represented in given
// number of digits in any base
// Returns true if 'num' can be
// represented using 'dig'
// digits in 'base'
function checkUtil($num, $dig, $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
function check($num, $dig)
{
// Check for all bases one by one
for ($base = 2; $base <= 32; $base++)
if (checkUtil($num, $dig, $base))
return true;
return false;
}
// Driver Code
$num = 8;
$dig = 3;
if (check($num, $dig) == true)
echo "Yes" ;
else
echo "No";
// This code is contributed by ajit
?>
JavaScript
<script>
// javascript program to check if a
// given number can be represented
// in given number of digits in any base
// Returns true if 'num' can be
// represented using 'dig' digits in 'base'
function checkUtil(num , dig , 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(parseInt(num / base), --dig, base);
return false;
}
// return true of num can be
// represented in 'dig' digits
// in any base from 2 to 32
function check(num , dig) {
// Check for all bases one by one
for (base = 2; base <= 32; base++)
if (checkUtil(num, dig, base))
return true;
return false;
}
// Driver code
var num = 8;
var dig = 3;
if (check(num, dig))
document.write("Yes");
else
document.write("No");
// This code contributed by Rajput-Ji
</script>
Output :
No
Time Complexity: O(32*32)
Auxiliary Space: O(1)
Optimized Approach:
we can optimize this program by adding a break statement in the check function to stop checking for bases once the number is found to be representable in a given number of digits in a particular base.
Here is a step-by-step approach to implement the above code:
Define the checkUtil function:
a. If dig is 1 and num is less than base, return true.
b. If dig is greater than 1 and num is greater than or equal to base, divide num by base and decrement dig by 1.
c. Recursively call checkUtil with the updated num, dig, and base.
d. If the recursive call returns true, return true.
e. Otherwise, return false.
Define the check function:
a. Iterate through all bases from 2 to 32:
i. Call checkUtil with the current num, dig, and base.
ii. If checkUtil returns true, return true.
iii. If the base is greater than or equal to num, break out of the loop.
b. If the loop completes without finding a suitable base, return false.
Define the main function:
a. Set num and dig to the desired values.
b. Call the check function with num and dig.
c. If check returns true, print "Yes" to the console.
d. Otherwise, print "No" to the console.
Compile and run the program to test it with various inputs.
Here's the optimized version of the program:
C++
#include <iostream>
using namespace std;
bool checkUtil(int num, int dig, int base)
{
if (dig == 1 && num < base)
return true;
if (dig > 1 && num >= base)
return checkUtil(num / base, --dig, base);
return false;
}
bool check(int num, int dig)
{
for (int base = 2; base <= 32; base++) {
if (checkUtil(num, dig, base))
return true;
if (base >= num)
break; // Stop checking if base is greater or equal to num
}
return false;
}
int main()
{
int num = 8;
int dig = 3;
(check(num, dig)) ? cout << "Yes" : cout << "No";
return 0;
}
Java
public class Main {
// Returns true if 'num' can be represented using 'dig'
// digits in 'base'
public static boolean 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 if num can be represented in 'dig'
// digits in any base from 2 to 32
public static boolean 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;
if (base >= num)
break; // Stop checking if base is greater or equal to num
}
return false;
}
// Driver program
public static void main(String[] args) {
int num = 8;
int dig = 3;
System.out.println(check(num, dig) ? "Yes" : "No");
}
}
Python3
def check_util(num, dig, base):
# Base case
if dig == 1 and 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 and num >= base:
return check_util(num // base, dig - 1, base)
return False
def check(num, dig):
# Check for all bases one by one
for base in range(2, 33):
if check_util(num, dig, base):
return True
if base >= num:
break # Stop checking if base is greater or equal to num
return False
# Driver program
num = 8
dig = 3
print("Yes" if check(num, dig) else "No")
C#
using System;
public class Mainn
{
// Returns true if 'num' can be represented using 'dig'
// digits in 'base'
public static bool checkUtil(int num, int dig, int baseVal)
{
// Base case
if (dig == 1 && num < baseVal)
return true;
// If there are more than 1 digits left and number
// is more than baseVal, then remove last digit by doing
// num / baseVal, reduce the number of digits and recur
if (dig > 1 && num >= baseVal)
return checkUtil(num / baseVal, --dig, baseVal);
return false;
}
// return true if num can be represented in 'dig'
// digits in any base from 2 to 32
public static bool check(int num, int dig)
{
// Check for all bases one by one
for (int baseVal = 2; baseVal <= 32; baseVal++)
{
if (checkUtil(num, dig, baseVal))
return true;
if (baseVal >= num)
break; // Stop checking if baseVal is greater or equal to num
}
return false;
}
// Driver program
public static void Main(string[] args)
{
int num = 8;
int dig = 3;
Console.WriteLine(check(num, dig) ? "Yes" : "No");
}
}
JavaScript
function check_util(num, dig, 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
// Math.floor(num / base), reduce the number of digits and recur
if (dig > 1 && num >= base)
return check_util(Math.floor(num / base), dig - 1, base);
return false;
}
function check(num, dig) {
// Check for all bases one by one
for (let base = 2; base <= 32; base++) {
if (check_util(num, dig, base))
return true;
if (base >= num)
break; // Stop checking if base is greater or equal to num
}
return false;
}
// Driver program
const num = 8;
const dig = 3;
console.log(check(num, dig) ? "Yes" : "No");
Output :
No
Time Complexity: O(d * (log n)^2) ,where n is the given number and d is the number of digits we want to check.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem