Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report

0

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;
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!