
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a given number can be represented in given a no. of digits in any base in C++
Suppose we have a number n, and number of digits d. We have to check whether the number n can be represented as d digit number in any base from 2 to 32. Suppose the number n is 8, and d = 4, then this can be represented as 1000 in binary, here the d is 4.
The idea is to check all bases one by one from 2 to 32. We can follow these steps to check the base.
- If the number is smaller than base, and digit is 1, then return true
- if digit is more than one and number is more than base, then remove the last digit from the number by doing num/base, thus reduce the number of digits, then recursively do this again and again.
- Otherwise return false.
Example
#include <iostream> using namespace std; bool isRepresentedInDDigits(int num, int d, int base) { if (d==1 && num < base) return true; if (d > 1 && num >= base) return isRepresentedInDDigits(num/base, --d, base); return false; } bool checkNumber(int num, int d) { // Check for all bases one by one for (int base=2; base<=32; base++) if (isRepresentedInDDigits(num, d, base)) return true; return false; } int main() { int num = 8; int dig = 2; if(checkNumber(num, dig)) cout << "Can be represented"; else cout << "Can not be represented"; }
Output
Can be represented
- Related Articles
- Check if a number is in given base or not in C++
- Check if a number can be represented as a sum of 2 triangular numbers in C++
- Find maximum number that can be formed using digits of a given number in C++
- Check if a given number divides the sum of the factorials of its digits in C++
- Check if a number can be represented as sum of non zero powers of 2 in C++
- C++ Pandigital Number in a Given Base
- Check if a given number is Pronic in C++
- Check if a given mobile number is fancy in C++
- Check if a given string is a valid number in C++
- C++ Program to check if a given number is Lucky (all digits are different)
- Find the largest number that can be formed with the given digits in C++
- Remove repeated digits in a given number using C++
- Maximize the given number by replacing a segment of digits with the alternate digits given in C++
- Check if any two intervals overlap among a given set of intervals in C++
- Check if the given array can be reduced to zeros with the given operation performed given number of times in Python

Advertisements