DEV Community

Mark
Mark

Posted on

How to Add and Simplify Fractions in JavaScript (with GCD and LCM)

Adding fractions looks trivial until you try to do it in code and end up with results like 0.5833333333333334 instead of 7/12. The clean way is to keep numerator and denominator as integers and use the greatest common divisor (GCD) and least common multiple (LCM).

1. GCD with Euclid's algorithm

const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
const lcm = (a, b) => Math.abs(a * b) / gcd(a, b);
Enter fullscreen mode Exit fullscreen mode

2. Adding two fractions

To add a/b + c/d, bring both to the common denominator lcm(b, d), add the numerators, then simplify with the GCD:

function addFractions(a, b, c, d) {
  const den = lcm(b, d);
  const num = a * (den / b) + c * (den / d);
  const g = gcd(num, den);
  return [num / g, den / g];
}

addFractions(1, 3, 1, 4); // [7, 12]
Enter fullscreen mode Exit fullscreen mode

3. Showing the steps to users

If you build an educational tool, the result alone is not enough. Students want to see the LCM, the converted fractions and the simplification. A good real-world example is Calculadora Alicia, a free Spanish step-by-step math solver. Its fraction calculator and LCM and GCD calculator show exactly these intermediate steps, which is a nice reference for how to present the output.

4. Edge cases to handle

  • Denominator of zero: throw an error instead of returning Infinity.
  • Negative fractions: keep the sign on the numerator.
  • Large numbers: use BigInt if inputs can exceed Number.MAX_SAFE_INTEGER.

With just gcd and lcm you can build addition, subtraction, multiplication and division of fractions that always return exact, simplified answers.

Top comments (0)