Re: Change for a Dollar
- From: Mark P <usenet@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 24 Apr 2007 20:22:39 -0700
Charles Richmond wrote:
Mark P wrote:Charles Richmond wrote:I heard one night on David Letterman that there are
293 ways to make change for a dollar. So I started
thinking about writing a program to list out *all*
the ways a dollar could be broken into change. I
just can *not* seem to get a hold on this problem.
I wrote a program with a recursive function attempting
to make the change, but it had excessive runtime and
does *not* seem to be working in any case...
Does anyone have an idea how I can proceed???
There are smarter ways to do it but a brain dead simple approach that ought to be fast enough on any machine built in the last twenty years...
int n_ways = 0;
for( n_50 = 0; n_50 <= 2; ++n_50)
for( n_25 = 0; n_25 <= 4; ++n_25)
for( n_10 = 0; n_10 <= 10; ++n_10)
for( n_5 = 0; n_5 <= 20; ++n_5)
if( n_50 * 50 + n_25 * 25 + n_10 * 10 + n_5 *5 <= 100)
++n_ways;
This may *count* the number of ways change can be made. I am
*not* sure that these loops do what you (or I) think they do.
I won't speak for you, but I'm certain that these loops do exactly what *I* think they do. What do you think they do?
But for my program, I want to *list* all the ways of making
change. So lines of the list might be:
I considered writing a follow-up post after I noticed that this is what you asked for, but then I thought it might make a fun exercise for the reader to let him (you) figure it out. But if you want me to ruin that potential fun, I will. Simply replace the line ++n_ways; with an appropriate print statement using the values of n_50, n_25, n_10, n_5 and an appropriately computed value for the number of pennies.
Mark
P.S. Incidentally, I ran my program and it computed 292 ways not 293, but perhaps Dave considers the original dollar to be the "missing" way?
.
- Follow-Ups:
- Re: Change for a Dollar
- From: mensanator@xxxxxxx
- Re: Change for a Dollar
- From: Charles Richmond
- Re: Change for a Dollar
- References:
- Change for a Dollar
- From: Charles Richmond
- Re: Change for a Dollar
- From: Mark P
- Re: Change for a Dollar
- From: Charles Richmond
- Change for a Dollar
- Prev by Date: Re: Change for a Dollar
- Next by Date: Re: a simple model checker
- Previous by thread: Re: Change for a Dollar
- Next by thread: Re: Change for a Dollar
- Index(es):
Relevant Pages
|