RosettaCodeData/Task/Long-multiplication/D/long-multiplication-2.d

32 lines
935 B
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
import std.stdio, std.algorithm, std.range, std.ascii, std.string;
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
auto longMult(in string x1, in string x2) pure nothrow @safe {
auto digits1 = x1.representation.retro.map!q{a - '0'};
immutable digits2 = x2.representation.retro.map!q{a - '0'}.array;
2013-06-05 21:47:54 +00:00
uint[] res;
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
foreach (immutable i, immutable d1; digits1.enumerate) {
2013-06-05 21:47:54 +00:00
foreach (immutable j, immutable d2; digits2) {
immutable k = i + j;
2013-04-10 21:29:02 -07:00
if (res.length <= k)
2013-06-05 21:47:54 +00:00
res.length++;
2013-04-10 21:29:02 -07:00
res[k] += d1 * d2;
if (res[k] > 9) {
if (res.length <= k + 1)
2013-06-05 21:47:54 +00:00
res.length++;
2013-04-10 21:29:02 -07:00
res[k + 1] = res[k] / 10 + res[k + 1];
res[k] -= res[k] / 10 * 10;
}
}
2013-06-05 21:47:54 +00:00
}
2013-04-10 21:29:02 -07:00
2013-10-27 22:24:23 +00:00
//return res.retro.map!digits;
return res.retro.map!(d => digits[d]);
2013-04-10 21:29:02 -07:00
}
void main() {
immutable two64 = "18446744073709551616";
2013-06-05 21:47:54 +00:00
longMult(two64, two64).writeln;
2013-04-10 21:29:02 -07:00
}