If I'm not wrong,David Martínez wrote:to get 10 cents I would need two 5cents coins.
Amount | No of 5 cents | No of 3 cents |
---|---|---|
11 | 1 | 2 |
12 | 0 | 4 |
13 | 2 | 1 |
21 | 3 | 2 |
27 | 3 | 4 |
Ganesh Patekar wrote:Sergiu Dobozi,
Welcome to CodeRanch!
Your logic is way better and short than I thought.
Sergiu Dobozi wrote:I tried to figure it out and with pen and paper and I can only do this with a for loop.
Let's say if you have the number 10, this program tests if 10-0*3 divides by 5, then assigns 10/5 the number of 5cents you need.
If you have 11 then 11-0*3 does not divide by 5. It's only when b=2 that it becomes true. so 11-2*3 divides by 5 and then you have the number of 3cents and you can pull out from the loop.
Junilu Lacar wrote:Good job working out the basic idea.
However, the solution provided is opaque and convoluted. It's really a lot simpler than that. Basically, you just keep subtracting 3 until you get a number that's evenly divisible by 5. The calculations can be done with two lines of code and another line of code to display the results.
[code]
void makeChangeFor(int num) {
int i = 0;
for (int n = num; n % 5 != 0; n -= 3, i++) /* empty loop body */ ;
System.out.printf("Change for %d cents => @%d 5 cents, @%d 3 cents%n", num, (num - i*3)/5, i);
}
Sergiu Dobozi wrote:That's great, I didn't know that one can write a for loop like this.
Junilu Lacar wrote:
Sergiu Dobozi wrote:That's great, I didn't know that one can write a for loop like this.
There are three kinds of actuaries: those who can count, and those who can't.
There are three kinds of actuaries: those who can count, and those who can't.
I love a woman who dresses in stainless steel ... and carries tiny ads:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
|