I found a piece of code that I was writing for interview prep few months ago.
According to the comment I had, it was trying to solve this problem:
Given some dollar value in cents (e.g. 200 = 2 dollars, 1000 = 10 dollars), find all the combinations of coins that make up the dollar value. There are only pennies, nickels, dimes, and quarters allowed. (quarter = 25 cents, dime = 10 cents, nickel = 5 cents, penny = 1 cent)
For example, if 100 was given, the answer should be:
4 quarter(s) 0 dime(s) 0 nickel(s) 0 pennies
3 quarter(s) 1 dime(s) 0 nickel(s) 15 pennies
etc.
This can be solved in both iterative and recursive ways, I believe. My recursive solution is quite buggy, and I was wondering how other people would solve this problem. The difficult part of this problem was making it as efficient as possible.
I know this is a very old question. I was searching through the proper answer and couldn't find anything that is simple and satisfactory. Took me some time but was able to jot down something.
This is a javascript solution and uses recursion.
I looked into this once a long time ago, and you can read my little write-up on it. Here’s the Mathematica source.
By using generating functions, you can get a closed-form constant-time solution to the problem. Graham, Knuth, and Patashnik’s Concrete Mathematics is the book for this, and contains a fairly extensive discussion of the problem. Essentially you define a polynomial where the nth coefficient is the number of ways of making change for n dollars.
Pages 4-5 of the writeup show how you can use Mathematica (or any other convenient computer algebra system) to compute the answer for 10^10^6 dollars in a couple seconds in three lines of code.
(And this was long enough ago that that’s a couple of seconds on a 75Mhz Pentium...)
Both: iterate through all denominations from high to low, take one of denomination, subtract from requried total, then recurse on remainder (constraining avilable denominations to be equal or lower to current iteration value.)
Duh, I feel stupid right now. Below there is an overly complicated solution, which I'll preserve because it is a solution, after all. A simple solution would be this:
Here is the other solution. This solution is based on the observation that each coin is a multiple of the others, so they can be represented in terms of them.
So, for 37 coins, for example:
I found this neat piece of code in the book "Python For Data Analysis" by O'reily. It uses lazy implementation and int comparison and i presume it can be modified for other denominations using decimals. Let me know how it works for you!
This is the improvement of Zihan's answer. The great deal of unnecessary loops comes when the denomination is just 1 cent.
It's intuitive and non-recursive.