Advertisement
nikunjsoni

483

May 20th, 2021
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     typedef long long ll;
  4.     typedef unsigned long long ull;
  5.     string smallestGoodBase(string n) {
  6.         ull tn = stoll(n);
  7.         ull ans;
  8.         for(int l=62; l>=1; l--){
  9.             if((1LL<<l) < tn)
  10.                 ans = search(tn, l);
  11.             if(ans == 0) continue;
  12.             return to_string(ans);
  13.         }
  14.         return to_string(tn-1);
  15.     }
  16.    
  17.     ll search(ull n, ull l){
  18.         ull left=1, right= ull(pow(1.0*n, 1.0/l)+1);
  19.         while(left<=right){
  20.             ull mid = (left+right)/2;
  21.             ull prod = 1, sum=1;
  22.             for(int d=1; d<=l && sum<=n; d++){
  23.                 prod *= mid;
  24.                 sum += prod;
  25.             }
  26.             if(sum == n)
  27.                 return mid;
  28.             else if(sum < n)
  29.                 left = mid+1;
  30.             else
  31.                 right = mid-1;
  32.         }
  33.         return 0;
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement