Skip to content
Advertisement

How to implement a division function without the operator, loop or recursion?

I need to convert this function using the functional programming paradigm but I don’t know how, I can use reducer or map creating an array but I don’t know how to implement it, i can’t use divide operator, loop or recursion;

function divide(dividend, divisor) {
  var result = 0;
  while (dividend >= divisor) {
    dividend -= divisor;
    result++;
  }
  return result;
}

console.log(divide(100, 2));

Advertisement

Answer

The way to do it declaratively is with a recursive function….

const divide = (t, b, depth = 0) => t < b ? depth : divide(t-b, b, depth+1);

console.log(`150 / 3 = ${divide(150, 3)}`);
console.log(`24 / 3 = ${divide(24, 3)}`);
console.log(`4 / 3 = ${divide(4, 3)}`);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement