<p>What is a <strong>non recursive</strong> algorithm for deciding whether a passed in amount can be built additively from a set of numbers.<br>
In my case I'm determining whether a certain currency amount (such as $40) can be met by adding up some combination of a set of bills (such as $5, $10 and $20 bills).  That is a simple example, but the algorithm needs to work for any currency set (some currencies use funky bill amounts and some bills may not be available at a given time).<br>
So $50 can be met with a set of ($20 and $30), but cannot be met with a set of ($20 and $40).  The non-recursive requirement is due to the target code base being for <code>SQL Server 2000</code> where the support of recursion is limited.<br>
In addition this is for supporting a multi currency environment where the set of bills available may change (think a foreign currency exchange teller for example).</p>

[{'answer_id': 64767, 'author': 'Arc the daft', 'author_id': 8615, 'author_profile': 'https://Stackoverflow.com/users/8615', 'pm_score': -1, 'selected': False, 'text': "<p><strong>Edit:</strong> The following will work <em>some</em> of the time.  Think about why it won't work all the time and how you might change it to cover other cases.</p>\n\n<p>Build it starting with the largest bill towards the smallest.  This will yeild the lowest number of bills.</p>\n\n<p>Take the initial amount and apply the largest bill as many times as you can without going over the price.</p>\n\n<p>Step to the next largest bill and apply it the same way.</p>\n\n<p>Keep doing this until you are on your smallest bill.</p>\n\n<p>Then check if the sum equals the target amount.</p>\n"}, {'answer_id': 64777, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 2, 'selected': False, 'text': "<p>You have twice stated that the algorithm cannot be recursive, yet that is the natural solution to this problem. One way or another, you will need to perform a search to solve this problem. If recursion is out, you will need to backtrack manually.</p>\n\n<p>Pick the largest currency value below the target value. If it's match, you're done. If not, push the current target value on a stack and subtract from the target value the picked currency value. Keep doing this until you find a match or there are no more currency values left. Then use the stack to backtrack and pick a different value.</p>\n\n<p>Basically, it's the recursive solution inside a loop with a manually managed stack.</p>\n"}, {'answer_id': 64785, 'author': 'Matthias Winkelmann', 'author_id': 4494, 'author_profile': 'https://Stackoverflow.com/users/4494', 'pm_score': 2, 'selected': False, 'text': "<p>That's a problem that can be solved by an approach known as dynamic programming. The lecture notes I have are too focused on bioinformatics, unfortunately, so you'll have to google for it yourself.</p>\n"}, {'answer_id': 64832, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 2, 'selected': False, 'text': '<p>This sounds like the subset sum problem, which is <a href="http://en.wikipedia.org/wiki/Subset_sum_problem" rel="nofollow noreferrer">known to be NP-complete</a>.</p>\n\n<p>Good luck with that.</p>\n\n<p><strong>Edit:</strong> If you\'re allowed arbitrary number of bills/coins of some denomination (as opposed to just one), then it\'s a different problem, and is easier.  See the <a href="http://en.wikipedia.org/wiki/Coin_problem" rel="nofollow noreferrer">coin problem</a>.  I realized this when reading another answer to a (suspiciously) similar question.</p>\n'}, {'answer_id': 64864, 'author': 'seanyboy', 'author_id': 1726, 'author_profile': 'https://Stackoverflow.com/users/1726', 'pm_score': 2, 'selected': False, 'text': "<p>If you treat each denomination as a point on a base-n number, where n is the maximum number of notes you would need, then you can increment through that number until you've exhausted the problem space or found a solution. </p>\n\n<p>The maximum number of notes you would need is the Total you require divided by the lowest denomination note. </p>\n\n<p>It's a brute force response to the problem, but it'll definitely work. </p>\n\n<p>Here's some p-code. I'm probably all over the place with my fence posts, and it's so unoptimized to be ridiculous, but it should work. I think the idea's right anyway. </p>\n\n<pre><code>Denominations = [10,20,50,100]\nRequired = 570\n\nDenominations = sort(Denominations)\niBase = integer (Required / Denominations[1])\n\nBumpList = array [Denominations.count]\nBumpList.Clear\n\nrepeat \n    iTotal = 0 \n    for iAdd = 1 to Bumplist.size\n        iTotal = iTotal + bumplist [iAdd] * Denominations[iAdd]\n    loop\n    if iTotal = Required then exit true\n\n    //this bit should be like a mileometer. \n    //We add 1 to each wheel, and trip over to the next wheel when it gets to iBase\n    finished = true\n    for iPos from bumplist.last to bumplist.first \n        if bumplist[iPos] = (iBase-1) then bumplist[iPos] = 0 \n        else begin\n            finished = false\n            bumplist[iPos] = bumplist[iPos]+1\n            exit for\n        end\n     loop \nuntil (finished)\n\nexit false    \n</code></pre>\n"}, {'answer_id': 65106, 'author': 'rjzii', 'author_id': 1185, 'author_profile': 'https://Stackoverflow.com/users/1185', 'pm_score': 1, 'selected': False, 'text': '<p>I agree with <a href="https://stackoverflow.com/questions/64723/i-need-an-algorithm-for-deciding-whether-a-passed-in-amount-can-be-built-additi#64832">Tyler</a> - what you are describing is a variant of the <a href="http://en.wikipedia.org/wiki/Subset_sum_problem" rel="nofollow noreferrer">Subset Sum</a> problem which is known to be <a href="http://en.wikipedia.org/wiki/NP-Complete" rel="nofollow noreferrer">NP-Complete</a>. In this case you are a bit lucky as you are working with a limited set of values so you can use <a href="http://en.wikipedia.org/wiki/Dynamic_programming" rel="nofollow noreferrer">dynamic programming</a> techniques here to optimize the problem a bit. In terms of some general ideas for the code:</p>\n\n<ul>\n<li>Since you are dealing with money, there are only so many ways to make change with a given bill and in most cases some bills are used more often than others. So if you store the results you can keep a set of the most common solutions and then just check them before you try and find the actual solution. </li>\n<li>Unless the language you are working with doesn\'t support recursion there is no reason to completely ignore the use of recursion in the solution. While any recursive problem can be solved using iteration, this is a case where recursion is likely going to be easier to write.</li>\n</ul>\n\n<p>Some of the other users such as <a href="https://stackoverflow.com/questions/64723/i-need-an-algorithm-for-deciding-whether-a-passed-in-amount-can-be-built-additi#64777">Kyle</a> and <a href="https://stackoverflow.com/questions/64723/i-need-an-algorithm-for-deciding-whether-a-passed-in-amount-can-be-built-additi#64864">seanyboy</a> point you in the right direction for writing your own function so you should take a look at what they have provided for what you are working on.</p>\n'}, {'answer_id': 405278, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>There's a difference between no recursion and limited recursion. Don't confuse the two as you will have missed the point of your lesson.</p>\n\n<p>For example, you can safely write a factorial function using recursion in C++ or other low level languages because your results will overflow even your biggest number containers within but a few recursions. So the problem you will face will be that of storing the result before it ever gets to blowing your stack due to recursion.</p>\n\n<p>This said, whatever solution you find - and I haven't even bothered understanding your problem deeply as I see that others have already done that - you will have to study the behaviour of your algorithm and you can determine what is the worst case scenario depth of your stack.</p>\n\n<p>You don't need to avoid recursion altogether if the worst case scenario is supported by your platform.</p>\n"}, {'answer_id': 405302, 'author': 'SharePoint Newbie', 'author_id': 21586, 'author_profile': 'https://Stackoverflow.com/users/21586', 'pm_score': -1, 'selected': False, 'text': '<p>Algorithm:\n1. Sort currency denominations available in descending order. <br />\n2. Calculate Remainder = Input % denomination[i] i -> n-1, 0 <br />\n3. If remainder is 0, the input can be broken down, otherwise it cannot be.<br /><br />\nExample:<br />\nInput: 50, Available: 10,20<br />\n[50 % 20] = 10, [10 % 10] = 0, Ans: Yes\nInput: 50, Available: 15,20<br />\n[50 % 20] = 10, [10 % 15] = 15, Ans: No</p>\n'}, {'answer_id': 405345, 'author': 'Gant', 'author_id': 12460, 'author_profile': 'https://Stackoverflow.com/users/12460', 'pm_score': 1, 'selected': False, 'text': '<p>You can deal with this problem with <strong>Dynamic Programming</strong> method as MattW. mentioned. </p>\n\n<p>Given limited number of bills and maximum amount of money, you can try the following solution. The code snippet is in C# but I believe you can port it to other language easily.</p>\n\n<pre><code>        // Set of bills\n        int[] unit = { 40,20,70};\n\n        // Max amount of money\n        int max = 100000;\n\n        bool[] bucket = new bool[max];\n\n        foreach (int t in unit)\n            bucket[t] = true;\n\n        for (int i = 0; i &lt; bucket.Length; i++)\n            if (bucket[i])\n                foreach (int t in unit)\n                    if(i + t &lt; bucket.Length)\n                        bucket[i + t] = true;\n\n        // Check if the following amount of money\n        // can be built additively\n        Console.WriteLine("15 : " + bucket[15]);\n        Console.WriteLine("50 : " + bucket[50]);\n        Console.WriteLine("60 : " + bucket[60]);\n        Console.WriteLine("110 : " + bucket[110]);\n        Console.WriteLine("120 : " + bucket[120]);\n        Console.WriteLine("150 : " + bucket[150]);\n        Console.WriteLine("151 : " + bucket[151]);\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>15 : False\n50 : False\n60 : True\n110 : True\n120 : True\n150 : True\n151 : False\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/64723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8852/']