Given three numbers A, B, and N, the task is to find the maximum possible value of floor(A * x / B) – A * floor(x / b) where x is a non-negative integer less than or equal to N. Here floor(T) = denotes the greatest integer not greater than the real number T (G.I.F function).
Constraints: 1 ≤ A ≤ 106, 1 ≤ B ≤ 1012, 1 ≤ N ≤ 1012. All values in input are integers.
Input: A = 5, B = 7, N = 4
The maximum value is obtained for the value x = 3. On substituting this value in the equation:
floor((5 * 3)/7) – (5 * floor(3 / 7)) = floor(2.1) – 0 = 2.
Input: A = 11, B = 10, N = 9
Naive Approach: The naive approach for this problem is to consider all the possible numbers from 1 to N and compute the maximum possible value.
Time Complexity: O(N).
Efficient Approach: The idea is to make an observation on the function f(x) = floor(A * x / B) – A * floor(x / B).
- We can observe that the given function is a periodic function. This can be proved by:
f(x + B) = floor(A * (x + B)/B) – A * floor((x + B)/B)
=> f(x + B) = floor((A * x / B) + A) – A * floor((x /B) + 1)
By floor-function property, floor(x + Integer) = Integer + floor(x).
=> f(x + B) = floor(A * x / B) – A * floor(x / B) = f(x)
- Hence, we can conclude that 0 ≤ x ≤ B. However, if x = B, f(x) = 0. So, we exclude it and get 0 ≤ x ≤ B-1.
- However, we must also consider the condition x ≤ N. Since floor(x) is a monotonically non-decreasing function, we must incorporate the best of both ranges.
- Hence, the maximum value of f(x) is obtained when x = min(B – 1, N).
Below is the implementation of the above approach:
Time Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.