Since you just need the logic to break the change into several
small units, I'm going to tell you how can you do the same,
Before we begin, you should be knowing the terms division and
modulus. Let me give you a little brief, in programming, a/b(read
as division) gives us the quotient and a%b(read as modulus) gives
us the reminder.
For example, 5/2 = 2 and 5 % 2= 1
Firstly let us assume that we want to break our change into 4
small units i.e. 10,5,2,1.
- we have to first calculate change / 10.
- If it is greater than 0 then we would save the value of change
/ 10 and calculate change % 10. From here we would get the
reminder. Now change = reminder.
- If it is 0, we repeat the same with 5,2 and 1.
- We stop when our change becomes 0
An example would clear.
So suppose if our change is 47,
- 47 / 10 = 4 which is greater than 0.
- Hence we save the value 4, it means that we need 4
coins of 10 pounds in our change. Now 47 % 10 = 7. So
now change = 7
- 7 /10 = 0. so we go to calculate 7 / 5.
- 7 / 5 = 1. so we need 4 coins of 10 pounds and 1
coin of 5 pounds in our change. Now 7 % 5 = 2. So now
change = 2.
- 2 / 10 = 0 and 2 / 5 = 0. So we go to calculate 2 /
2
- 2 / 2 = 1, so we need 4 coins of 10 pounds, 1 coin
of 5 pounds and 1 coin of 2 pounds n our change.
- Now, 1 % 2 = 0. So. now change = 0 and since change became 0.
we stopped.
Solution ends.
Please comment and let me know if you have any further
doubts. Please upvote this answer if you like it.
Thank you.
Have a good day.