Polynomial long division: Difference between revisions

Updated D entry
(Updated D entry)
Line 687:
((0 . -123)) ; -123</lang>
=={{header|D}}==
<lang d>import std.stdio, std.range, std.algorithm, std.typecons, std.array;
 
Tuple!(double[], double[]) polyDiv(in double[] inN, in double[] inD)
/*pure /*nothrow*/ {
// codeCode smell: a function that does two things.
static int trimAndDegree(T)(ref T[] poly) /*nothrow pure*/ {
poly.length -= poly.retro().countUntilfind!q{ a != 0b }(0.0).retro;
return (cast(int)poly.length) - 1;
}
 
double[] N = inN.dup; // Not nothrow.
const(double)[] D = inD;
const dD = trimAndDegree(D);
auto dN = trimAndDegree(N);
double[] q, r;
if (dD < 0)
throw new ExceptionError("ZeroDivisionError");
if (dN >= dD) {
//q = repeat([0.0)].takereplicate(dN).array();
q = std.array.replicate([0.0], dN);
while (dN >= dD) {
auto d = repeatstd.array.replicate([0.0).take(], dN - dD).array() ~ D;
constimmutable mult = q[dN - dD] = N[$ - 1] / d[$ - 1];
d[] *= mult;
N[] -= d[];
dN = trimAndDegree(N);
}
} else {
q = [0.0];
return tuple(q, rN);
}
}
r = N;
 
return tuple(q, r);
 
int trimAndDegree1(T)(ref T[] poly) nothrow pure {
poly.length -= poly.retro.countUntil!q{ a != 0 };
return (cast(int)poly.length) - 1;
}
 
Line 723 ⟶ 728:
immutable N = [-42.0, 0.0, -12.0, 1.0];
immutable D = [-3.0, 1.0, 0.0, 0.0];
writefln("%s / %s = %s remainder %s", N, D, polyDiv(N, D).tupleof[]);
}</lang>
{{out}}