Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the Sum of fractions - JavaScript
In JavaScript, we can calculate the sum of fractions by finding a common denominator and adding the numerators. This tutorial shows how to add fractions represented as arrays without converting to decimals.
Problem Statement
Given an array of arrays where each subarray contains two numbers representing a fraction, we need to find their sum in fraction form.
const arr = [[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]]; // Represents fractions: 12/56, 3/45, 23/2, 2/6, 2/8
Algorithm Overview
To add fractions a/b + c/d, we use the formula: (a*d + c*b) / (b*d), then simplify by dividing by the greatest common divisor (GCD).
Implementation
Step 1: GCD Function
First, we need a function to find the greatest common divisor to simplify fractions:
const gcd = (a, b) => {
let num = 2, res = 1;
while(num
GCD of 12 and 8: 4
GCD of 15 and 25: 5
Step 2: Fraction Addition Function
This function adds two fractions and returns the simplified result:
const sumFrac = (a, b) => {
const aDenom = a[1], aNumer = a[0];
const bDenom = b[1], bNumer = b[0];
let resDenom = aDenom * bDenom;
let resNumer = (aDenom * bNumer) + (bDenom * aNumer);
const greatestDivisor = gcd(resDenom, resNumer);
return [resNumer/greatestDivisor, resDenom/greatestDivisor];
};
// Test adding two fractions: 1/2 + 1/3 = 5/6
console.log("1/2 + 1/3 =", sumFrac([1, 2], [1, 3]));
1/2 + 1/3 = [ 5, 6 ]
Step 3: Complete Solution
Now we combine everything to sum an array of fractions:
const arr = [[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]];
const gcd = (a, b) => {
let num = 2, res = 1;
while(num {
const aDenom = a[1], aNumer = a[0];
const bDenom = b[1], bNumer = b[0];
let resDenom = aDenom * bDenom;
let resNumer = (aDenom * bNumer) + (bDenom * aNumer);
const greatestDivisor = gcd(resDenom, resNumer);
return [resNumer/greatestDivisor, resDenom/greatestDivisor];
};
const sumArrayOfFractions = arr => {
return arr.reduce((acc, val) => sumFrac(acc, val));
};
const result = sumArrayOfFractions(arr);
console.log("Sum of all fractions:", result);
console.log("As decimal:", result[0] / result[1]);
Sum of all fractions: [ 1731, 140 ]
As decimal: 12.364285714285714
How It Works
The solution uses reduce() to iteratively add fractions. Each step:
- Takes two fractions [a, b] and [c, d]
- Calculates (a*d + c*b) / (b*d)
- Simplifies using GCD
- Returns the simplified fraction
Conclusion
This approach maintains precision by keeping fractions in their exact form rather than converting to decimals. The GCD ensures results are in their simplest form.
