Logo

Programming-Idioms

  • Java
  • Pascal
  • C#

Idiom #75 Compute LCM

Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.

int gcd(int a, int b)
{
  while (b != 0)
  {
    int t = b;
    b = a % t;
    a = t;
  }
  return a;
}

int lcm(int a, int b)
{
  if (a == 0 || b == 0)
    return 0;
  return (a * b) / gcd(a, b);
}

int x = lcm(140, 72);
import java.math.BigInteger;
BigInteger a = new BigInteger("123456789");
BigInteger b = new BigInteger("987654321");
BigInteger x = a.multiply(b).divide(a.gcd(b));
#include <gmp.h>
mpz_t _a, _b, _x;
mpz_init_set_str(_a, "123456789", 10);
mpz_init_set_str(_b, "987654321", 10);
mpz_init(_x);

mpz_lcm(_x, _a, _b);
gmp_printf("%Zd\n", _x);

New implementation...
< >
deleplace