84.5k views
5 votes
Suppose we wanted to make change for purchases and wanted to use the least number of coins possible. Here is a greedy algorithm: for the change amount due, we always use the largest-face-value coin first. Assume we have only coins of quarters ($.25), twenties ($.20), and pennies ($.01). Assume the change is $.40: a. what would be the coins and their numbers obtained by the greedy algorithm above

1 Answer

4 votes

Answer:

Step-by-step explanation:

The following code is a Python function that takes in the amount of change. Then it uses division and the modulo operator to calculate the number of coins that make up the changes, using the greatest coin values first.

import math

def amountOfCoins(change):

print("Change: " + str(change))

quarters = math.floor(change / 0.25)

change = change % 0.25

dimes = math.floor(change / 0.20)

change = change % 0.20

pennies = math.floor(change / 0.01)

print("Quarters: " + str(quarters) + "\\Dimes: " + str(dimes) + "\\Pennies: " + str(pennies))

Suppose we wanted to make change for purchases and wanted to use the least number-example-1
User Jglouie
by
5.0k points