165B - Burning Midnight Oil - CodeForces Solution


binary search implementation *1500

Please click on ads to support us..

Python Code:

def calc(num, k):
    sum = 0
    i = 0
    while k**i <= num:
        sum += int(num/ k**i)
                i+=1
    return sum


def Binary(sum, k):
    l = 0
    r = 10**9
    while l<r:
        mid = int(l +(r - l)/2)
        ans = calc(mid, k)
        if ans < sum:
            l = mid + 1
        else:
            r = mid
    return l



list=[int(item) for item in input().split()]
sum = list[0]
k = list[1]
print(Binary(sum, k))

C++ Code:

#include<iostream>

using namespace std;

typedef long long int ll;
const int N = 100000000000;

int main()
{
	ll n, m, x, k;
	ll high, low, mid, ans, cnt;

    cin >> n >> k;

	high = n; low = 1; ans = N;
	while (low <= high)
	{
		mid = (high + low) / 2;

		cnt = mid;
        m = k;
		while (true)
		{
			x = mid / m; m *= k;
			cnt += x;

			if (!x) break;
        }

		if (cnt == n) {
			ans = mid;
			break;
		}

		if (cnt > n) ans = min(ans, mid), high = mid - 1;
		else low = mid + 1;
	}
    cout << ans << "\n";
	return 0;
}

		 	  		 		  			    	 			  			


Comments

Submit
0 Comments
More Questions

1729B - Decode String
1729C - Jumping on Tiles
1729E - Guess the Cycle Size
553B - Kyoya and Permutation
1729D - Friends and the Restaurant
1606C - Banknotes
580C - Kefa and Park
342A - Xenia and Divisors
1033A - King Escape
39D - Cubical Planet
1453A - Cancel the Trains
645A - Amity Assessment
1144A - Diverse Strings
1553B - Reverse String
1073A - Diverse Substring
630N - Forecast
312B - Archer
34D - Road Map
630I - Parking Lot
160B - Unlucky Ticket
371B - Fox Dividing Cheese
584B - Kolya and Tanya
137B - Permutation
550C - Divisibility by Eight
5A - Chat Servers Outgoing Traffic
615A - Bulbs
5B - Center Alignment
549A - Face Detection
535B - Tavas and SaDDas
722C - Destroying Array