- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

# 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 −

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' ]

- Related Articles
- Prime digits sum of a number in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- Represent a number as a Sum of Maximum Possible Number of Prime Numbers in C++
- Weekday as a number in JavaScript?
- Product sum difference of digits of a number in JavaScript
- Express the following rational number as a decimal.$frac{1}{16}$.
- Express $-frac{7}{8}$ As a rational number with denominator 40
- Express ( frac{3}{4} ) as a rational number with denominator ( -60 ).
- Give an example of each of two irrational numbers whose sum is a rational number.
- Sum array of rational numbers and returning the result in simplest form in JavaScript
- Validate a number as Fibonacci series number in JavaScript
- Is a number sum of two perfect squares in JavaScript
- Destructively Sum all the digits of a number in JavaScript
- Count ways to express a number as sum of powers in C++
- Recursive sum all the digits of a number JavaScript

Advertisements