C++ program to find in how many bases we can represent the number not greater than M

C++Server Side ProgrammingProgramming

Suppose we have a numeric string S, and another number M. Let d be the greatest digit in S. We have to find in many different integers not greater than M can be found by choosing an integer n not less than d+1 and seeing S as a base-n number?

So, if the input is like S = "999"; M = 1500, then the output will be 3, because S as base 10 number, we get 999, as base 11 number, we get 1197, as base 12 number, we get 1413. These three values are the only ones that we can obtain and are not greater than 1500.

Steps

To solve this, we will follow these steps −

if size of S is same as 1, then:
   if numeric value of S <= M, then:
      return 1
   Otherwise
      return 0
d := 0
for each character c in S, do
   d := maximum of d and (c - ASCII of '0')
left := d
right := M + 1
while right - left > 1, do:
   mid := (left + right) / 2
   v := 0
   for each character c in S, do
      if v > M / mid, then:
         v := M + 1
      Otherwise
         v := v * mid + (c - ASCII of '0')
   if v <= M, then:
      left := mid
   Otherwise
      right := mid
return left - d

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(string S, int M){
   if (S.size() == 1){
      if (stoi(S) <= M)
         return 1;
      else
         return 0;
   }
   int d = 0;
   for (char c : S)
      d = max(d, int(c - '0'));
   long left = d;
   long right = M + 1;
   while (right - left > 1){
      long mid = (left + right) / 2;
      long v = 0;
      for (char c : S){
         if (v > M / mid)
            v = M + 1;
         else
            v = v * mid + (c - '0');
      }
      if (v <= M)
         left = mid;
      else
         right = mid;
   }
   return left - d;
}
int main(){
   string S = "999";
   int M = 1500;
   cout << solve(S, M) << endl;
}

Input

"999", 1500

Output

3
raja
Updated on 03-Mar-2022 06:48:09

Advertisements