您有不限量的面值A和B美元的钞票(A不等于B) 。您想使用正好N张钞票总共支付S元。任务是找到您需要的价值A澳元的纸币数量。如果没有解决方案,则返回-1 。
例子:
Input: A = 1, B = 2, S = 7, N = 5
Output: 3
3 * A + 2 * B = S
3 * 1 + 2 * 2 = 7
Input: A = 2, B = 1, S = 7, N = 5
Output: 2
Input: A = 2, B = 1, S = 4, N = 5
Output: -1
Input: A = 2, B = 3, S = 20, N = 8
Output: 4
方法:设x为需要的价值A的票据的数目,然后其余票据,即N – x必须为价值B的票据。由于它们的总和要求为S,因此必须满足以下方程式:
S = (A * x) + (B * (N – x))
Solving the equation further,
S = (A * x) + (B * N) – (B * x)
S – (B * N) = (A – B) * x
x = (S – (B * N)) / (A – B)
After solving for x, it is the number of notes of value A required
only if the value of x is an integer else the result is not possible.
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the amount of notes
// with value A required
int bankNotes(int A, int B, int S, int N)
{
int numerator = S - (B * N);
int denominator = A - B;
// If possible
if (numerator % denominator == 0)
return (numerator / denominator);
return -1;
}
// Driver code
int main()
{
int A = 1, B = 2, S = 7, N = 5;
cout << bankNotes(A, B, S, N) << endl;
}
// This code is contributed by mits
Java
// Java implementation of the approach
class GFG {
// Function to return the amount of notes
// with value A required
static int bankNotes(int A, int B, int S, int N)
{
int numerator = S - (B * N);
int denominator = A - B;
// If possible
if (numerator % denominator == 0)
return (numerator / denominator);
return -1;
}
// Driver code
public static void main(String[] args)
{
int A = 1, B = 2, S = 7, N = 5;
System.out.print(bankNotes(A, B, S, N));
}
}
Python3
# Python3 implementation of the approach
# Function to return the amount of notes
# with value A required
def bankNotes(A, B, S, N):
numerator = S - (B * N)
denominator = A - B
# If possible
if (numerator % denominator == 0):
return (numerator // denominator)
return -1
# Driver code
A, B, S, N = 1, 2, 7, 5
print(bankNotes(A, B, S, N))
# This code is contributed
# by mohit kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the amount of notes
// with value A required
static int bankNotes(int A, int B,
int S, int N)
{
int numerator = S - (B * N);
int denominator = A - B;
// If possible
if (numerator % denominator == 0)
return (numerator / denominator);
return -1;
}
// Driver code
public static void Main()
{
int A = 1, B = 2, S = 7, N = 5;
Console.Write(bankNotes(A, B, S, N));
}
}
// This code is contributed by Akanksha Rai
PHP
3