David Angarita
David Angarita

Reputation: 910

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));

Upvotes: 0

Views: 348

Answers (3)

David Angarita
David Angarita

Reputation: 910

My Final solution is this:

const adition = (a, b) => a + b;

const subtraction = (a, b) => a - b;

const multiplication = (a, b) => {
    return b >= 0 ? [...Array(b)].reduce((acc) => adition(acc, a), 0) : [...Array(a)].reduce((acc) => adition(acc, b), 0);
};

const division = (a, b) => {
    return a === 0 || b === 0 ? 'Error' : b > 1 ? [...Array(a).keys()].reduce((acc, num) => multiplication(num, b) <= a ? adition(acc, 1) : acc, -1) : a;
};

Upvotes: 0

customcommander
customcommander

Reputation: 18921

I'm a bit puzzled by the requirements. My understanding is that loops or recursion aren't prohibited in functional programming. Assuming this is an exercise (it has to be) then here's another way to look at it:

To solve a / b you can count how many b you can fit in a. So for example:

10 / 2 -> [2, 2, 2, 2, 2] -> 5

or:

            +2 +2 +2 +2 (map)
10 / 2 -> [2, 4, 6, 8, 10] -> 5
           ^           ^^
          (x)         (pred)

So we can unfold the divisor into a list of sums of itself:

const unfold = (pred, map, x) => {
  const ys = [];
  for (let y = x; pred(y); y = map(y)) ys.push(y);
  return ys;
}

unfold(x => x <= 10, x => x + 2, 2);
//=> [2, 4, 6, 8, 10]

Now we can implement divide with unfold and return the length of the list:

const divide = (a, b) =>
  unfold(x => x <= a, x => x + b, b)
    .length;

divide(10, 2);
//=> 5

Upvotes: 1

danh
danh

Reputation: 62676

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)}`);

Upvotes: 2

Related Questions