Open In App

Addition of Two Fractions using JavaScript

Fraction numbers in math are representations of parts of a whole, consisting of a numerator (the part being considered) and a denominator (the total number of equal parts). Add two fractions a/b and c/d and print the answer in simplest form.

Examples: 

Input:  1/2 + 3/2
Output: 2/1

Input: 1/3 + 3/9
Output: 2/3

Using Math Operations

In this approach, we use basic math operations to find the common denominator, calculate the sum of the numerators, simplify the fraction by finding the greatest common divisor (GCD), and then display the result in the console.

Steps:

Example: The example below uses Math Operations to add two fractions using JavaScript.

let num1 = 1;
let den1 = 5;
let num2 = 3;
let den2 = 15;
let commonDen = den1 * den2;
let newNum1 = num1 * (commonDen / den1);
let newNum2 = num2 * (commonDen / den2);
let res = newNum1 + newNum2;
let gcd = function (a, b) {
    return b === 0 ? a : gcd(b, a % b);
};
let div = gcd(res, commonDen);
res /= div;
commonDen /= div;
console.log(`${num1}/${den1} + ${num2}/${den2} is equal to ${res}/${commonDen}`);

Output
1/5 + 3/15 is equal to 2/5

Time Complexity: O(log(min(den1, den2)))

Auxiliary Space: O(1)

Using Fractions Library (fraction.js)

In this approach using the fraction.js library, we first create fraction objects for the given numerators and denominators. Then, we add these fractions using the add method provided by the library. Finally, we convert the result fraction to its simplest form using toFraction and display it in the console along with the input fractions.

Install the fraction.js library using the below command:

npm i fraction.js

Steps:

Example: The below example uses Fractions Library to perform the Addition of two fractions using JavaScript.

const Fraction = require('fraction.js');
let num1 = 1;
let den1 = 500;
let num2 = 2;
let den2 = 1500;
let frac1 = new Fraction(num1, den1);
let frac2 = new Fraction(num2, den2);
let tempRes = frac1.add(frac2);
let res = tempRes.toFraction();
console.log(`${num1}/${den1} + ${num2}/${den2} is equal to ${res}`);

Output

1/500 + 2/1500 is equal to 1/300

Time Complexity: O(1)

Auxiliary Space: O(1)

Article Tags :