Check if a number N starts with 1 in b-base in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 27-Sep-2019 10:47:57
Advertisements