I am writing a function to calculate change given – $1, $5, $10, $20, $50, and $100 are the types of bills I have available to me. Each denomination is also subtracted from a finite number of bills that are in the drawer at the current time.
There are also no pennies, nickels, dimes, or quarters to deal with here, just whole dollar amounts.
This is what I came up with:
UPDATE
The function now has a correction for error handling when there are no more bills in the drawer for any denomination, the user is supplied with a message to obtain more money for the drawer.
// Set elsewhere in the program
int numberOnesLeft;
int numberFivesLeft;
int numberTensLeft;
int numberTwentiesLeft;
int numberFiftiesLeft;
int numberHundredsLeft;
int numberOfOnes = 0;
int numberOfFives = 0;
int numberOfTens = 0;
int numberOfTwenties = 0;
int numberOfFifties = 0;
int numberOfHundreds = 0;
void CalculateChange(float amount)
{
char tempStr[128];
while(amount >= 100.0)
{
if(numberOfHundreds >= numberHundredsLeft)
break;
else
amount = amount - 100.0;
numberOfHundreds++;
}
while(amount >= 50.0)
{
if(numberOfFifties >= numberFiftiesLeft)
break;
else
amount = amount - 50.0;
numberOfFifties++;
}
while(amount >= 20.0)
{
if(numberOfTwenties >= numberTwentiesLeft)
break;
else
amount = amount - 20.0;
numberOfTwenties++;
}
while(amount >= 10.0)
{
if(numberOfTens >= numberTensLeft)
break;
else
amount = amount - 10.0;
numberOfTens++;
}
while(amount >= 5.0)
{
if(numberOfFives >= numberFivesLeft)
break;
else
amount = amount - 5.0;
numberOfFives++;
}
while(amount >= 1.0)
{
if(numberOfOnes >= numberOnesLeft)
break;
else
amount = amount - 1.0;
numberOfOnes++;
}
if(amount > 0)
{
printf("You are still owed: $");
sprintf(tempStr, "%.2f", amount);
printf(tempStr);
printf("\n\n");
printf("Please obtain more money for the drawer\n");
}
}
From the valued correction of arasmussen, the Big O of this is O(x*n) = x * O(n) = O(n), where x is the number of denominations there are.
Is there a algorithmically faster way for computing each denomination?
Less loops?
With infinite bills, should be simple enough.
With finite numbers of bills…