How to use Math Operations In Javascript

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:

  • Multiply the denominators of the fractions to obtain a common denominator.
  • Scale the numerators by the corresponding factor to match the common denominator.
  • Add the adjusted numerators to find the sum of the fractions.
  • Use the greatest common divisor (GCD) to simplify the resulting fraction by dividing both the numerator and denominator by their GCD.

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

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)

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

Table of Content

  • Using Math Operations
  • Using Fractions Library (fraction.js)

Similar Reads

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....

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....