Count the number of currency notes needed in C++

C++Server Side ProgrammingProgramming

Given an amount in rupees that one has to pay, say pay_rupees and an unlimited amount of banknotes that have value as Rupees_amount_1 and Rupees_amount_2. The goal is to pay pay_rupees using exactly the total number of notes=distribution_total and count the number of type Rupees_amount_1 notes required. If there is no solution to pay then return −1 as answer.

For Example

Input

Rupees_amount_1 = 1, Rupees_amount_2 = 5, pay_Rupees = 11 distribution_total = 7

Output

Count of number of currency notes needed are − 6

Explanation

6*1 + 5*1 = 11 and notes=6+1=7

Input

Rupees_amount_1 = 2, Rupees_amount_2 = 3, pay_Rupees = 10 distribution_total = 4

Output

Count of number of currency notes needed are: 2

Explanation

2*2 + 3*2 = 10 and notes=2+2=4

Approach used in the below program is as follows

Let a1 be the number of notes of amount rupees 1and N be the total number of notes. To make the payment of P, we will have equations − 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) If a1 is integer then only we will have a solution else return −1.

  • Take all numbers as input.

  • Function notes_needed(int Rupees_amount_1, int Rupees_amount_2, int pay_Rupees, int distribution_total) takes all inputs and returns the count of the number of currency notes needed.

  • Take the initial count as 0.

  • Take total = pay_Rupees − (Rupees_amount_2 * distribution_total)

  • Set total_given = Rupees_amount_1 − Rupees_amount_2

  • Set total_given = Rupees_amount_1 − Rupees_amount_2

  • If total % total_given == 0 then return count as total / total_given.

  • Else return −1.

Example

 Live Demo

#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);
}

Output

If we run the above code it will generate the following output −

Count the number of currency notes needed are− 6
raja
Published on 05-Jan-2021 07:27:11
Advertisements