给定三个数字A,B和N ,任务是找到floor(A * x / B)– A * floor(x / b)的最大可能值,其中x是小于或等于的非负整数N.这里floor(T)=表示不大于实数T的最大整数(GIF函数)。
约束条件:1个≤A≤10 6,1≤乙≤10 12,1≤N≤10 12。输入中的所有值都是整数。
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
朴素方法:针对此问题的朴素方法是考虑从1到N的所有可能数字,并计算最大可能值。
时间复杂度: O(N)。
高效方法:想法是观察函数f(x)= floor(A * x / B)– A * floor(x / B) 。
- 我们可以观察到给定的函数是周期函数。这可以通过以下方式证明:
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)
- 因此,我们可以得出0≤x≤B的结论。但是,如果x = B,则f(x)=0。因此,我们将其排除,得到0≤x≤B-1。
- 但是,我们还必须考虑条件x≤N。由于floor(x)是单调非递减函数,因此我们必须结合两个范围中的最佳值。
- 因此,当x = min(B – 1,N)时,将获得f(x)的最大值。
下面是上述方法的实现:
C++
// C++ Program to find the maximum
// possible value for the given function
#include
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;
}
Java
// Java program to find the maximum
// possible value for the given function
class GFG{
// Function to return the maximum
// value of f(x)
public static int floorMax(int A, int B, int N)
{
int x = Math.min(B - 1, N);
return (A * x) / B;
}
// Driver Code
public static void main(String[] args)
{
int A = 11, B = 10, N = 9;
System.out.println(floorMax(A, B, N));
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program to find the maximum
# possible value for the given function
# Function to return the maximum
# value of f(x)
def floorMax(A, B, N):
x = min(B - 1, N)
return (A * x) // B
# Driver code
A = 11
B = 10
N = 9
print(floorMax(A, B, N))
# This code is contributed by code_hunt
C#
// C# program to find the maximum
// possible value for the given function
using System;
using System.Collections.Generic;
class GFG{
// Function to return the maximum
// value of f(x)
static int floorMax(int A, int B, int N)
{
int x = Math.Min(B - 1, N);
return (A * x) / B;
}
// Driver Code
public static void Main (string[] args)
{
int A = 11, B = 10, N = 9;
Console.Write(floorMax(A, B, N));
}
}
// This code is contributed by rutvik_56
9
时间复杂度: O(1)