
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a number N starts with 1 in b-base in C++
We have a number N and a base b. In this program we have to check whether the number is starting with 1 in base b or not. Suppose a number 6 is given. In binary this is 110, so it starts with 1, in base 4 also it will be 124. Here also it starts with 1.
As we know, if a number N is represented in base b, b gets converted to m+1 bit sequence bm bm-1 … b0. This implies bm bm + bm-1 * bm-1 + … + b0*b0 = N. The largest number will be 2*bm – 1. The N lies in bm ≤ N ≤ 2*bm – 1. Now another thing to notice is that m cannot exceed $\lfloor\log_2 m\;\rfloor$ this is because when we represent any number in base-2 it gets converted into a sequence of only 0s and 1s, so the length of this sequence will always be greater than any other base representation and its length will be equal to$\lfloor\log_2 m\;\rfloor+1$ . So to check for a given number N starts with 1 in base b or not we will traverse from m = 1 to m =$\lfloor\log_2 m\;\rfloor$ and check whether for any value of m, N lies in the range bm ≤ N ≤ 2*bm – 1 or not and accordingly return True or false.
Example
#include <iostream> #include <cmath> using namespace std; bool isStartWithOne(int number, int base) { int m = log2(number); for (int i = 1; i <= m; i++) { if (number >= pow(base, i) && number <= 2 * pow(base, i) - 1) //if number is in the given range return true; } return false; } int main() { int num = 19, base = 16; if(isStartWithOne(num, base)){ cout << "Can be represented"; }else{ cout << "Can not be represented"; } }
Output
Can be represented
- Related Questions & Answers
- Check if a string starts with given word in PHP
- Check if a number can be expressed as a^b in C++
- Check if a number is in given base or not in C++
- Check if a string follows a^n b^n pattern or not in Python
- Find the Number of Trailing Zeroes in base B Representation of N! using C++
- Count number of triplets (a, b, c) such that a^2 + b^2 = c^2 and 1<=a<=b<=c<= n in C++
- Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B in C++
- Program to check if N is a Pentagonal Number in C++
- Check if a number can be expressed as a^b in Python
- Check if a number has bits in alternate pattern - Set 1 in C++
- Construct Deterministic PDA for a^n b^n where n>=1
- Check if a String starts with any of the given prefixes in Java
- Construct a Turing Machine for L = {a^n b^n | n>=1}
- How to check if a string starts with a specified Prefix string in Golang?
- Check if a number is power of k using base changing methods in C++