用 C++ 统计所需的货币纸币数量
给定一个需要支付的金额(以卢比为单位),例如 pay_rupees,以及数量无限的面额为 Rupees_amount_1 和 Rupees_amount_2 的钞票。目标是使用恰好等于 distribution_total 的总钞票数量来支付 pay_rupees,并计算所需的 Rupees_amount_1 钞票数量。如果没有解决方案可以支付,则返回 -1 作为答案。
例如
输入
Rupees_amount_1 = 1, Rupees_amount_2 = 5, pay_Rupees = 11 distribution_total = 7
输出
Count of number of currency notes needed are − 6
解释
6*1 + 5*1 = 11 and notes=6+1=7
输入
Rupees_amount_1 = 2, Rupees_amount_2 = 3, pay_Rupees = 10 distribution_total = 4
输出
Count of number of currency notes needed are: 2
解释
2*2 + 3*2 = 10 and notes=2+2=4
下面程序中使用的方案如下 −
设 a1 为面额为 rupees 1 的钞票数量,N 为钞票总数。要支付 P,我们将有以下方程 − a1*(Rupees_amount_1) + (N−a1)*(Rupees_amount_2) = P P=a1*(Rupees_amount_1) + (N)*(Rupees_amount_2) − (a1)*(Rupees_amount_2) P − (N)*(Rupees_amount_2) =a1*(Rupees_amount_1) − (a1)*(Rupees_amount_2) a1= P − (N)*(Rupees_amount_2) / ( Rupees_amount_1 − Rupees_amount_2) 如果 a1 是整数,则我们才有解,否则返回 -1。
将所有数字作为输入。
函数 notes_needed(int Rupees_amount_1, int Rupees_amount_2, int pay_Rupees, int distribution_total) 获取所有输入并返回所需的货币纸币数量。
将初始计数设置为 0。
取 total = pay_Rupees − (Rupees_amount_2 * distribution_total)
设置 total_given = Rupees_amount_1 − Rupees_amount_2
设置 total_given = Rupees_amount_1 − Rupees_amount_2
如果 total % total_given == 0,则返回计数为 total / total_given。
否则返回 -1。
示例
#include<bits/stdc++.h>
using namespace std;
int notes_needed(int Rupees_amount_1, int Rupees_amount_2, int pay_Rupees, int
distribution_total){
int count = 0;
int total = pay_Rupees − (Rupees_amount_2 * distribution_total);
int total_given = Rupees_amount_1 − Rupees_amount_2;
if (total % total_given == 0){
count = total / total_given;
return count;
} else {
return −1;
}
}
int main(){
int Rupees_amount_1 = 1;
int Rupees_amount_2 = 5;
int pay_Rupees = 11;
int distribution_total = 7;
cout<<"Count of number of currency notes needed are: "<<notes_needed(Rupees_amount_1, Rupees_amount_2, pay_Rupees, distribution_total);
}输出
如果我们运行以上代码,它将生成以下输出 −
Count the number of currency notes needed are− 6
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP