Find the maximum possible value for the given periodic function

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
Output: 2
Explanation:
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
Output: 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 the ranges.
  • Hence, the maximum value of f(x) is obtained when x = min(B – 1, N).

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to find the maximum 
// possible value for the given function
  
#include <iostream>
using namespace std;
  
// Function to return the maximum 
// value of f(x)
int floorMax(int A, int B, int N)
{
    int x = min(B - 1, N);
  
    return (A * x) / B;
}
  
// Driver code
int main()
{
    int A = 11, B = 10, N = 9;
  
    cout << floorMax(A, B, N);
    return 0;
}

chevron_right


Output:

9

Time Complexity: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : abhasbind, Akanksha_Rai