Skip to content

Instantly share code, notes, and snippets.

@kyle-pena-nlp
Created December 17, 2025 17:32
Show Gist options
  • Select an option

  • Save kyle-pena-nlp/b6d1c5fe71d6279900d9d2962e011877 to your computer and use it in GitHub Desktop.

Select an option

Save kyle-pena-nlp/b6d1c5fe71d6279900d9d2962e011877 to your computer and use it in GitHub Desktop.
Find quotient without multiplication or division
function findQuotientRec(dividend, factors, offset, indices) {
i = 0;
while (factors[i] > dividend) {
i += 1;
}
if (i < factors.length) {
dividend -= factors[i];
indices.push(offset + i);
findQuotientRec(dividend, factors.slice(i), offset + i, indices);
}
}
/**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
var divide = function(dividend, divisor) {
const absDividend = Math.abs(dividend);
const signDividend = Math.sign(dividend);
const absDivisor = Math.abs(divisor);
const signDivisor = Math.sign(divisor);
let factor = Math.abs(absDivisor);
const factors = [];
const powers = [];
let powerEntry = 1;
while (factors.length <= 32) {
factors.unshift(factor);
powers.unshift(powerEntry);
factor = factor + factor;
powerEntry = powerEntry + powerEntry;
}
// `factors` is now [d * 1, d * 2, d * 4, d * 8, d * 16, ..., d * 2^31] where d = divisor
// `powers` is now [1, 2, 4, 8, 16, ..., 2^31 ]
// Any multiple of dividend is expressable as a bitmask on a vector of powers of two
// So we need to find out which bitmask on `factors` gives the largest number less than dividend
// This is stored in `indices`
const indices = [];
findQuotientRec(absDividend, factors, 0, indices);
let quotient = 0;
for (const index of indices) {
quotient += powers[index];
}
// Recover the signs
const signedQuotient = signDivisor * signDividend * quotient;
const MAX = Math.pow(2,31)-1;
const MIN = -Math.pow(2,31);
if (signedQuotient > MAX) {
return MAX;
}
else if (signedQuotient < MIN) {
return MIN;
}
else {
return signedQuotient;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment