Skip to content

Instantly share code, notes, and snippets.

@alanrsoares
Last active June 27, 2019 00:06
Show Gist options
  • Save alanrsoares/500525f6c454ceeb5c2d111014bb3d55 to your computer and use it in GitHub Desktop.
Save alanrsoares/500525f6c454ceeb5c2d111014bb3d55 to your computer and use it in GitHub Desktop.
Multiplication with no multiplication, using range reduce
const isInt = n => parseInt(n) === n;
const toPrecisionN = precision => value =>
Number(value.toPrecision(precision));
function multiplyInt(a, b) {
const iterable = [...Array(Math.abs(Math.floor(a)))];
return iterable.reduce(
acc => a < 0
? acc - b
: acc + b,
0
);
}
function multiply(a, b) {
if (isInt(b) && !isInt(a)) {
// invert operands for algorhythmic short-circuit
return multiplyInt(b, a);
}
const maxpPrecision = 5;
const toPrecision = toPrecisionN(maxpPrecision);
const intProduct = multiplyInt(a, b);
if (!isInt(a)) {
const a$ = parseInt(a) - a;
const precisionFactor = Math.pow(10, maxpPrecision);
const restProduct = multiplyInt(multiply(precisionFactor, a$), b);
const absRestProduct = Math.abs(restProduct / precisionFactor);
return toPrecision(intProduct + absRestProduct);
} else {
return toPrecision(intProduct);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment