//how to reduce a fraction javascript
// Function to find the Greatest Common Divisor (GCD) using the Euclidean algorithm
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to reduce a fraction
function reduceFraction(numerator, denominator) {
if (denominator === 0) {
throw new Error("Denominator cannot be zero.");
}
// Handle negative signs
const sign = (numerator * denominator < 0) ? -1 : 1;
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
const commonDivisor = gcd(numerator, denominator);
return {
numerator: (numerator / commonDivisor) * sign,
denominator: denominator / commonDivisor
};
}
// Example usage:
const fraction1 = reduceFraction(8, 12);
console.log(`${fraction1.numerator}/${fraction1.denominator}`); // Output: 2/3
const fraction2 = reduceFraction(20, 200);
console.log(`${fraction2.numerator}/${fraction2.denominator}`); // Output: 1/10
const fraction3 = reduceFraction(330, 2050);
console.log(`${fraction3.numerator}/${fraction3.denominator}`); // Output: 33/205
const fraction4 = reduceFraction(-6, 9);
console.log(`${fraction4.numerator}/${fraction4.denominator}`); // Output: -2/3
Explanation:
gcd(a, b) function:
This function calculates the greatest common divisor of two numbers a and b using the Euclidean algorithm. It repeatedly replaces the larger number with the remainder of the division until the remainder is 0. The last non-zero remainder is the GCD.
reduceFraction(numerator, denominator) function:
It first checks if the denominator is zero to prevent division by zero errors.
It determines the sign of the resulting fraction to correctly handle negative numerators or denominators.
It then takes the absolute values of the numerator and denominator for GCD calculation.
It calls the gcd function to find the greatest common divisor.
Finally, it divides both the numerator and denominator by the commonDivisor and returns an object containing the reduced numerator and denominator. The sign is applied back to the numerator.