Count the coins: Difference between revisions

+ new second D entry
(Updated third D entry)
(+ new second D entry)
Line 354:
 
=={{header|D}}==
===Minimal versionVersion===
{{trans|Go}}
<lang d>import std.stdio, std.bigint;
Line 371:
writeln(changes(1000_00, [100, 50, 25, 10, 5, 1]));
}</lang>
{{out}}
Output:
<pre>242
13398445413854501</pre>
 
===FasterSafe versionUlong Version===
This version is very similar to the precedent, but it uses a faster ulong type, and performs a checked sum to detect overflows at run-time.
<lang d>import std.stdio, core.checkedint;
 
auto changes(int amount, int[] coins, ref bool overflow) {
auto ways = new ulong[amount + 1];
ways[0] = 1;
foreach (coin; coins)
foreach (j; coin .. amount + 1)
ways[j] = ways[j].addu(ways[j - coin], overflow);
return ways[amount];
}
 
void main() {
bool overflow = false;
changes( 1_00, [25, 10, 5, 1], overflow).writeln;
if (overflow)
"Overflow".puts;
overflow = false;
changes( 1000_00, [100, 50, 25, 10, 5, 1], overflow).writeln;
if (overflow)
"Overflow".puts;
}</lang>
The output is the same.
 
===Faster Version===
{{trans|C}}
<lang d>import std.stdio, std.bigint;