0

John has 5.10 in quarters, dimes and nickels. If he has 31 coins what are possibilities?

This is my code:

#include <stdio.h>

int main() {
    int quarters, dimes, nickels;
    for (quarters = 1; quarters <= 31; quarters++) {
        for (dimes = 1; dimes <= 31; dimes++) {
            for (nickels = 1; nickels <= 31; nickels++) {
                if (quarters + dimes + nickels == 31 && quarters * .25 + dimes * .10 + nickels * .05 == 5.10) {
                    printf("%i quarters, %i dimes, %i nickels \n", quarters, dimes, nickels);
                }
            }
        }
    }
}

Gives the result:

14 quarters, 15 dimes, 2 nickels
15 quarters, 11 dimes, 5 nickels
17 quarters, 3 dimes, 11 nickels

My question is why does this code give 4 solutions?

#include <stdio.h>

int main() {
    int quarters, dimes, nickels;
    for (quarters = 1; quarters <= 31; quarters++) {
        for (dimes = 1; dimes <= 31; dimes++) {
            for (nickels = 1; nickels <= 31; nickels++) {
                if (quarters + dimes + nickels == 31 && quarters * 25 + dimes * 10 + nickels * 5 == 510) {
                    printf("%i quarters, %i dimes, %i nickels \n", quarters, dimes, nickels);
                }
            }
        }
    }
}

Result:

14 quarters, 15 dimes, 2 nickels
15 quarters, 11 dimes, 5 nickels
16 quarters, 7 dimes, 8 nickels
17 quarters, 3 dimes, 11 nickels
P123
  • 107
  • 1
  • 7
  • 1
    There is a difference between 510 and 5.10. You have to pay attention to that. – Module Oct 25 '16 at 17:11
  • 1
    BTW, since you know the total count is 31, you only need two loops: `for (quarters = 0; quarters <= 31; ++quarters) for (dimes = 0; dimes <= 31-quarters; ++dimes) { nickels = 31 - dimes - quarters; /* test here */ }`. – Toby Speight Oct 25 '16 at 17:18
  • @Pranav, Shouldn't you be starts at zero rather than one? – ikegami Oct 25 '16 at 17:23
  • @ikegami I could if I wanted to have zero coins at the start – P123 Oct 25 '16 at 17:25
  • @Pranav, That's my point. It seems that you should want to. There's nothing in the question that says John must have at least one nickel, one dime and one quarter. Also, heed Toby Speight's advice. There's no reason to make 32*32*32=32768 checks when 32*(32*33)/2=16896 would suffice. – ikegami Oct 25 '16 at 17:33
  • Alright, thanks for the help guys – P123 Oct 25 '16 at 17:37
  • You can further optimize by using at most `min(31, floor(510/25)) = 20` quarters. Any more and you'll bust. – ikegami Oct 25 '16 at 17:38
  • @ikegami Exceptional C implementations do use decimal floating point. Doubt OP will see such a platform soon. – chux - Reinstate Monica Oct 25 '16 at 17:39

1 Answers1

1

5/100 and 10/100 are periodic numbers in binary just like 1/3 is a periodic number in decimal. This means it's impossible to represent them exactly as floating point numbers.

ikegami
  • 367,544
  • 15
  • 269
  • 518