Minimize value of a in series a, a/b^1, a/b^2, a/b^3, …, a/b^n such that sum of initial non-zero terms becomes at least S
Given two integers b and S. The task is to find the minimum value of ‘a‘ such that sum of becomes equal or greater than ‘S‘ for initial non-zero terms.
a, a/b1, a/b2, a/b3, …………., a/bn
Input: b = 2, S = 4
- Let a = 1, S = 1/20 + 1/21 = 1 + 0 = 1 < 4.
- Let a =2, S = 2/20 + 2/21 + 2/22 = 2 + 1 + 0 = 3 < 4.
- Let a = 3, S = 3/20 + 3/21 + 3/22 = 3 + 1 + 0 = 4 = S.
So, a = 3 is the answer.
Input: b = 8, S = 25
Approach: This problem can be solved using binary search to find the answer. Obviously, if the number ‘a‘ is an answer, then every number n > a is also an answer because the values would only become more but we need the find the minimum one. So, to check some number ‘a’ we can use the formula given in the problem itself. Follow the steps below to solve the problem:
- Initialize the variables a as 1, low as 0, and high as S.
- Traverse in a while loop till low is less than equal to high and perform the following tasks:
- Initialize the variable mid as the average of low and high.
- Initialize x as b and sum as mid.
- Traverse in a while loop till mid/x is greater than 0 and perform the following tasks:
- Add the value of mid/x to the variable sum.
- Multiply the value b to the variable x.
- If sum is greater than equal to S then set a as mid and high as mid-1.
- Else set low as mid+1.
- After performing the above steps, print the value of a as the answer.
Below is the implementation of the above approach:
Time Complexity: O(log2N)
Auxiliary Space: O(1)