# Refactoring Pset1 Greedy Modulo

I've got Pset 1, 'Greedy' working, I just think I can refactor it better. How can I get rid of ints a, b, c and d?

a = amount /25; amount = amount % 25;

b = amount /10; amount = amount % 10;

c = amount /5; amount = amount % 5;

d = amount /1; amount = amount & 1;

coins = (a+b+c+d);

where amount is the rounded amount inputted.

Thanks

• Two side questions. What is the purpose of `amount = amount & 1;` at the end? The `&` operator is a bit shift operator. I can't figure out what you were doing here, or is it a typo? Fortunately, it has no effect on the program since amount isn't used after this. Second, what happens when you divide any number by 1? ;-) Dec 13, 2017 at 23:57

Use multiple while loops to solve it.

e.g. for dimes.....

``````//Checking for dime usage
while (amount >= 10)
{
amount = amount - 10;
coins = coins + 1;
printf("amount = %d\ncoins = %i\n",amount,coins);
}
``````

or pennies..

``````//Checking for penny usage
while (amount > 0)
{
amount = amount - 1;
coins = coins + 1;
printf("amount = %d\ncoins = %i\n",amount,coins);
}
``````

If this was helpful, Please vote up and mark as accepted by clicking.

Regards, Nathan

• While loops will work, the technique that ExpertShaun used is far more efficient. The improvement, as @curiouskiwi suggested, is to use a single var, coins, to accumulate the coins, eliminating the need for a,b,c and d. Consider this. Say that the amount is \$1,000,000. A loop would have to execute 4 million times to get the answer. With ExpertShaun's technique, the program executes exactly 8 calculations, no matter what the starting amount of cash. It could be simplified to 7, but I'll leave that for anyone else to figure out for themselves. ;-) (don't post it here.) Dec 13, 2017 at 23:45

You could simply use `coins` as the variable that holds the coin value and add to it with each equation.

``````coins = 0;
coins += amount/25; ...
coins += amount/10 ....   etc etc.
``````

Then, at the end, `coins` will already be the total.