- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

Following is the code −

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

Following is the console output −

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

- Related Questions & Answers
- Find LCM of rational number in C++
- Sum array of rational numbers and returning the result in simplest form in JavaScript
- Represent a number as a Sum of Maximum Possible Number of Prime Numbers in C++
- Weekday as a number in JavaScript?
- Digit sum upto a number of digits of a number in JavaScript
- Prime digits sum of a number in JavaScript
- Validate a number as Fibonacci series number in JavaScript
- Count ways to express a number as sum of powers in C++
- Product sum difference of digits of a number in JavaScript
- Count ways to express a number as sum of consecutive numbers in C++
- Represent a Number as Sum of Minimum Possible Pseudo-Binary Numbers in C++
- Recursive sum all the digits of a number JavaScript
- Destructively Sum all the digits of a number in JavaScript
- Is a number sum of two perfect squares in JavaScript
- Program to show decimal number from rational number representation in C++

Advertisements