top of page
Caută
Poza scriitoruluioanaunciuleanu

The Minimum number of Coins Algorithm in C++


An algorithm to find the minimum number of coins / banknotes for a specific value.



// Number of coins

#include <bits/stdc++.h>
using namespace std;

double moneyValues[] = { 0.1, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500 };
int numberOfCoinsinCirculation = sizeof(moneyValues) / sizeof(moneyValues[0]);

void changeMoney(double sum)
{
    double initialSum = sum;
    vector<double> coins;
    for (int i = numberOfCoinsinCirculation - 1; i >= 0; i--)
    {
        while (sum >= moneyValues[i])
        {
            sum -= moneyValues[i];
            coins.push_back(moneyValues[i]);
        }
   }

   //Print the result
   cout << "The coins/banknotes needed to sum up " << initialSum << " is: \t";
   int counter = 0;
   int coinsCounter = 0;
   int banknotesCounter = 0;
   for (int i = 0; i < coins.size(); i++)
   {
       double currentAmount = coins[i];
        cout << currentAmount << "\t";
        counter++;
        if(currentAmount >= 1.0)
        {
            banknotesCounter++;
        }
        else
        {
            coinsCounter++;
        }
   }

    cout << endl;
    cout<< "The number of coins/banknotes is: " << counter << endl;
    if(coinsCounter == 1)
    {
       cout << coinsCounter << " Coin" << endl;
    }
    else
    {
        cout << coinsCounter << " Coins" << endl;
    }

    if(banknotesCounter == 1)
    {
        cout << banknotesCounter << " Banknote" << endl;
    }
    else
    {
        cout << banknotesCounter << " Banknotes" << endl;
    }

}

int main(){
   double numberToChange = 236.9;
   changeMoney(numberToChange);
   return 0;
}

The coins/banknotes needed to sum up 236.9 is:  200     20      10      5       1       0.5     0.1     0.1     0.1
0.1
The number of coins/banknotes is: 10
5 Coins
5 Banknotes

29 afișări0 comentarii

Postări recente

Afișează-le pe toate

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed...

Comments


bottom of page