01-addition-of-fractions
Problem Description
You are given four parameters: numer1
and denom1
, representing the numerator and the denominator of the first fraction, and numer2
and denom2
, representing the numerator and the denominator of the second fraction. Your task is to complete a function called 'solution'. This function should add the two fractions and express the result as a simplified fraction. The function should then return an array containing the numerator and denominator of the result in that order.
Constraints
All parameters (numer1, denom1, numer2, denom2) are greater than 0 and less than 1,000.
Input/Output Examples
numer1 | denom1 | numer2 | denom2 | result |
---|---|---|---|---|
1 | 2 | 3 | 4 | [5, 4] |
9 | 2 | 1 | 3 | [29, 6] |
Explanation of Input/Output Examples
-
Example #1 1 / 2 + 3 / 4 equals 5 / 4. Therefore, you should return [5, 4].
-
Example #2 9 / 2 + 1 / 3 equals 29 / 6. Therefore, you should return [29, 6].
My Solution
function solution(numer1, denom1, numer2, denom2) {
// Calculate denominator and numerator of the sum
let numer = numer1 * denom2 + numer2 * denom1;
let denum = denom1 * denom2;
// Start checking for common divisor from the smallest of the two numbers
let divisor = denom < numer ? denom : numer;
// Loop from the largest possible divisor down to 1
while (true) {
// If divisor is a common divisor of both numerator and denominator
if (denum % divisor === 0 && numer % divisor === 0) {
return [numer / divisor, denum / divisor];
}
// If not, decrement the divisor and try again
divisor--;
}
}