Skip to main content

GCD / LCM Calculator

Find the greatest common divisor and least common multiple of two numbers.

Reviewed by · Last reviewed

Using the GCD and LCM Calculator

  1. Fill the First Number and Second Number inputs with any integers you want the GCD and LCM of. Negative signs and zero are both allowed; the tool normalises to absolute values before computing.
  2. Press Calculate or hit Enter. The GCD and LCM appear side by side, along with the identity |a × b| = GCD(a, b) × LCM(a, b) filled in with your numbers so you can see the relationship.
  3. Read the step log below the result. Every division in Euclid's algorithm is shown as a = bq + r, making the process inspectable for homework or teaching.
  4. Re-run with different inputs as often as you want; nothing is stored between calculations.
  5. Copy any line of the step log with a click, which is handy when pasting the derivation into a LaTeX document or chat message.

The Euclidean Algorithm in Code

The GCD routine implements Euclid's algorithm with the remainder variant: while the second operand is non-zero, replace (a, b) with (b, a mod b); the final value of a is the GCD. JavaScript's % operator returns a value with the sign of the dividend, so the absolute-value normalisation at the top of the function keeps the loop invariant clean. The LCM is then computed as |a * b| / gcd, with the division done before the multiplication where possible to avoid intermediate overflow, i.e. (a / gcd) * b.

Both routines run in the browser without any network call. The step log is built during the iteration by pushing each { a, b, q, r } tuple into an array, which is then rendered as a list. The overall cost is O(log min(a, b)) divisions, the worst case being a pair of consecutive Fibonacci numbers - a result proved by Gabriel Lamé in 1844 and considered the first complexity analysis in the history of the field.

Where GCD and LCM Show Up in Real Work

  • Reducing a fraction to lowest terms by dividing numerator and denominator by their GCD.
  • Finding a common denominator for fraction addition, which is just the LCM of the two denominators.
  • Computing the period of two recurring events - a bus every 12 minutes and another every 18 minutes meet again every LCM(12, 18) = 36 minutes.
  • Checking coprimality (GCD = 1) before applying the Chinese Remainder Theorem or choosing an RSA exponent.
  • Reducing a gear ratio, a pulley ratio, or a music-theory interval to its canonical form.
  • Working out how many tiles of size a by b fit into a larger rectangle without cutting - a GCD problem.

Boundary Cases

  • GCD(a, 0) = |a| for any integer a, because every integer divides zero. The tool returns |a| cleanly rather than hitting an infinite loop.
  • GCD(0, 0) is conventionally defined as 0, since no positive integer can be called "greatest". The tool follows this convention.
  • LCM with a zero operand is 0, matching the convention that every non-zero number divides 0 so the "least common multiple" that is a multiple of 0 is just 0.
  • Negative inputs are handled by taking absolute values up front. GCD and LCM are conventionally non-negative in the integers.
  • Very large inputs up to Number.MAX_SAFE_INTEGER (253-1) work exactly. For larger magnitudes, switch to BigInt or a CAS.
  • Coprime pairs produce GCD = 1 and LCM = |a * b|, which is the maximum possible LCM for a given product; this is a small but useful sanity check.

Background: Two Thousand Years of the Same Algorithm

Euclid stated the algorithm in Proposition VII.1 of the Elements (circa 300 BCE) using subtraction rather than the modulus operation: repeatedly replace the larger of (a, b) by the difference with the smaller until they are equal. The modulus-based variant used here is faster for operands of very different sizes but mathematically identical. Lamé's 1844 theorem bounds the number of iterations by five times the number of decimal digits of the smaller operand, which is why even ten-digit inputs need fewer than 50 steps. The extended Euclidean algorithm goes further and also returns integers x, y such that a·x + b·y = GCD(a, b); this Bézout coefficient form is what makes modular inverses and RSA key generation possible. This tool returns the GCD and LCM only, not the Bézout coefficients.

Alternatives and Tradeoffs

Python's math.gcd and math.lcm, JavaScript's own BigInt-based solutions, and command-line tools like bc or factor will all compute GCD and LCM faster for scripted use. For gigantic operands with hundreds of digits the binary GCD (Stein's algorithm) is worth knowing because it avoids divisions in favour of bit shifts and subtractions - historically useful on hardware with slow division. For symbolic or polynomial GCDs (useful in computer algebra) you want SymPy, Mathematica, or Maxima. The browser tool wins when you have two manageable integers and want the answer plus the derivation without opening a REPL. Show-your-work transcripts are its distinguishing feature.

Frequently Asked Questions

Why is GCD(0, 0) treated as zero?

Zero is divisible by every integer, so "greatest common divisor" of zero and zero has no largest element in the positive integers. The modern algebraic convention, followed here, is to set GCD(0, 0) = 0 and treat it as the identity for the GCD operation under the divisibility lattice. Some older sources leave it undefined, but that would require a runtime error for a perfectly meaningful algebraic input.

How fast does the algorithm run?

The Euclidean algorithm performs <em>O</em>(log min(a, b)) modulus operations. Gabriel Lam&eacute; proved in 1844 that the worst case is a pair of consecutive Fibonacci numbers, and the step count is bounded by about five times the number of decimal digits of the smaller operand. Even for both inputs at <code>Number.MAX_SAFE_INTEGER</code> the calculation finishes in microseconds, so the only perceptible delay is rendering the step log.

Is the calculation done on a server?

No. The Preact component contains the entire algorithm; there is no fetch call, no WebSocket, and no backend service. Your numbers are never transmitted. If you open browser DevTools and watch the Network tab during a calculation, you will see zero outbound requests.

Why does GCD(a, b) * LCM(a, b) equal |a * b|?

Write <em>a</em> and <em>b</em> as products of primes: <em>a</em> = &prod; <em>p</em><sub>i</sub><sup>&alpha;<sub>i</sub></sup>, <em>b</em> = &prod; <em>p</em><sub>i</sub><sup>&beta;<sub>i</sub></sup>. The GCD takes the minimum exponent at each prime, the LCM takes the maximum. Summing min and max gives the sum of the two exponents, so multiplying GCD by LCM rebuilds <em>a</em>&middot;<em>b</em>. This identity is what lets the tool compute LCM from GCD in constant time rather than doing a second pass.

What is the extended Euclidean algorithm and is it supported?

The extended Euclidean algorithm returns not just GCD(<em>a</em>, <em>b</em>) but also integers <em>x</em> and <em>y</em> such that <em>a</em>&middot;<em>x</em> + <em>b</em>&middot;<em>y</em> = GCD(<em>a</em>, <em>b</em>). These B&eacute;zout coefficients are essential for modular inverses (and therefore RSA). This tool computes the GCD and LCM only; if you need the coefficients, a small Python snippet with <code>math.gcd</code> and a back-substitution loop, or SymPy&apos;s <code>gcdex</code>, will give them to you.

Can I use this to simplify fractions?

Yes. Compute the GCD of the numerator and denominator, then divide both by it. The result is in lowest terms. This tool is the manual-step companion to the site&apos;s fraction calculator, which does the full simplification in one pass.

Do negative numbers behave specially?

No. Both inputs are reduced to absolute values before the algorithm runs, and GCD and LCM are reported as non-negative integers, matching the standard mathematical convention. So GCD(-12, 8) = 4 and LCM(-12, 8) = 24, exactly as if the negatives had been positive.

What is Stein&apos;s binary GCD and when would I prefer it?

Stein&apos;s algorithm (1967) replaces the modulus operation with bit shifts and subtractions. If both operands are even, both are halved; if one is even, it is halved; otherwise the smaller is subtracted from the larger. This avoids integer division, which historically was expensive on hardware. For 32-bit and 64-bit integers the speed difference is negligible; for 1024-bit BigInts or larger, Stein&apos;s variant can be measurably faster.

How does the tool format the step log?

Each step shows <code>a = b * q + r</code> with the current remainder highlighted. When <em>r</em> reaches zero, the previous <em>r</em> is the GCD. This is the standard schoolbook layout, identical to what a teacher would write on a blackboard. You can copy any line with one click, handy for pasting into a homework submission or chat.

How big can the inputs be?

Any integer up to <code>Number.MAX_SAFE_INTEGER</code>, which is 9,007,199,254,740,991. Above that, JavaScript&apos;s <code>number</code> type loses integer precision and both the modulus operation and the output become unreliable. For genuinely larger inputs, use a BigInt implementation in Node.js, Python&apos;s arbitrary-precision integers, or a dedicated CAS.

More Math & Calculators