Decomposing rational number as a sum of rationals in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of exactly two numbers.

The first element specifies the numerator of any rational number and the second element specifies the denominator of the same.

Our function should return an array of any number of sub arrays of two elements each such that when the rational number specified by the subarray are added they sum up to the input rational number and the numerator of all the subarrays should be 1.

We also need to make sure that the number of subarrays is as small as possible.

Example

Following is the code −

 Live Demo

const num = '2/3';
const decompose = (num = '') => {
   const fractions = [];
   let res = eval(num);
   if (res >= 1) {
      fractions = ['' + Math.floor(res)];
      res = res - Math.floor(res);
   };
   let sum = 0;
   let denom = 2;
   while (sum <= res - 0.000000001) {
      if (1 / denom + sum <= res) {
         fractions.push("1/" + denom);
         sum += 1 / denom;
      }
      denom++;
   }
   return fractions;
}
console.log(decompose(num));

Output

Following is the console output −

[ '1/2', '1/6' ]

Updated on: 19-Apr-2021

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements