Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
- Elixir
- Elixir
- C
- Clojure
- C++
- C++
- C#
- C#
- D
- D
- Dart
- Dart
- Fortran
- Go
- Haskell
- Haskell
- Haskell
- JS
- Java
- Lua
- Lua
- PHP
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
- VB
defmodule Gcd do
def gcd(x, 0), do: x
def gcd(x, y), do: gcd(y, rem(x,y))
end
x = Gcd.gcd(a, b)
x = Integer.gcd(a, b)
mpz_t _a, _b, _x;
mpz_init_set_str(_a, "123456789", 10);
mpz_init_set_str(_b, "987654321", 10);
mpz_init(_x);
mpz_gcd(_x, _a, _b);
gmp_printf("%Zd\n", _x);
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod a b))))
unsigned long long int GCD(unsigned long long int a, unsigned long long int b)
{
unsigned long long int c=a%b;
if(c==0)
return b;
return GCD(b, c);
}
This implementation is the cleanest I know, but it is not meant for negative integers.
auto x = std::gcd(a, b);
C++17 or later
Uses the absolute values of a and b in calculations
Uses the absolute values of a and b in calculations
int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int gcd(int a, int b)
{
while (b != 0)
{
int t = b;
b = a % t;
a = t;
}
return a;
}
x = gcd(a, b);
This is the standard way to compute gcd, however it doesn't work with std.bigints right now (https://issues.dlang.org/show_bug.cgi?id=7102)
BigInt gcd(in BigInt x, in BigInt y) pure {
if (y == 0)
return x;
return gcd(y, x%y);
}
gcd(a, b);
As this time, std.numeric.gcd doesn't work with BigInts. Here is a non-optimal but working implementation.
x = a.gcd(b);
int gcd(int a, int b) {
while (b != 0) {
var t = b;
b = a % t;
a = t;
}
return a;
}
function gcd(m,n) result(answer)
implicit none
integer(kind=int64),intent(in) :: m, n
integer(kind=int64) :: answer,irest,ifirst
ifirst=iabs(m)
answer=iabs(n)
if(answer.eq.0)then
answer=ifirst
else
do
irest = mod(ifirst,answer)
if(irest == 0) exit
ifirst = answer
answer = irest
enddo
answer= iabs(answer)
endif
end function gcd
gcd a b
| a==b =a
| a>b = gcd(a-b) b
| otherwise = gcd a (b-a)
x = gcd a b
gcd x y = gcd' (abs x) (abs y)
where
gcd' a 0 = a
gcd' a b = gcd' b (a `rem` b)
const gcd = (a, b) => b === 0 ? a : gcd (b, a % b)
Warning: This implementation is not the most efficient. Figure out a more efficient way to do this if you're up for it!
function gcd(a, b)
return b==0 and a or gcd(b,a%b)
end
function gcd(x, y)
if (y == 0) then
return x
else
return gcd(y, x%y)
end
end
function GCD(a,b:int64):int64;
var t:int64;
begin
while b <> 0 do
begin
t := b;
b := a mod b;
a := t;
end;
result := a;
end;
Using the Euklid Algorithm
x = math.gcd(a, b)
Starting with Python 3.5 the gcd-function is part of the math-library
x = a.gcd(b)