Programming-Idioms

Implementation
Elixir

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating resource.

Please try to avoid dependencies to third-party libraries and frameworks.

Implementation edit is for fixing errors and enhancing with metadata.

Instead of changing the code of the snippet, consider creating another Elixir implementation.

Other implementations
import "math/big"
gcd.GCD(nil, nil, a, b)
x.Div(a, gcd).Mul(x, b)
from fractions import gcd
x = (a*b)//gcd(a, b)
extern crate num;

use num::Integer;
use num::bigint::BigInt;
let x = a.lcm(&b);
x = lcm(a, b);

int lcm(int a, int b) => (a * b) ~/ gcd(a, b);

int gcd(int a, int b) {
  while (b != 0) {
    var t = b;
    b = a % t;
    a = t;
  }
  return a;
}
x = a.lcm(b)
x = lcm a b
import std.numeric: gcd
uint x = (a * b) / gcd(a, b);
gcd(A,B) when A == 0; B == 0 -> 0;
gcd(A,B) when A == B -> A;
gcd(A,B) when A > B -> gcd(A-B, B);
gcd(A,B) -> gcd(A, B-A).

lcm(A,B) -> (A*B) div gcd(A, B).
const gcd = (a, b) => b === 0 ? a : gcd (b, a % b)
let x = (a * b) / gcd(a, b)
(setf x (lcm a b))
sub gcd {
	my ($x, $y) = @_;
	while ($x) { ($x, $y) = ($y % $x, $x) }
	$y
}
 
sub lcm {
	my ($x, $y) = @_;
	($x && $y) and $x / gcd($x, $y) * $y or 0
}
sub lcm {
	use integer;
	my ($x, $y) = @_;
	my ($f, $s) = @_;
	while ($f != $s) {
		($f, $s, $x, $y) = ($s, $f, $y, $x) if $f > $s;
		$f = $s / $x * $x;
		$f += $x if $f < $s;
	}
	$f
}
#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);
extension=gmp
$gcd = gmp_lcm($a, $b);
echo gmp_strval($gcd);
#include <numeric>
auto x = std::lcm(a, b);
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));