用 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

更新於: 2021年1月5日

565 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.