templates/gcd-lcm-extended-gcd.cpp
compilable
$cat templates/gcd-lcm-extended-gcd
GCD, LCM & Extended GCD
GCD, LCM, Extended Euclidean algorithm, and linear Diophantine equation solver.
#gcd#lcm#extended-gcd#diophantine#bezout
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll gcd(ll a, ll b) {
while (b) { a %= b; swap(a, b); }
return a;
}
ll lcm(ll a, ll b) {
return a / gcd(a, b) * b;
}
ll extgcd(ll a, ll b, ll &x, ll &y) {
if (!b) { x = 1; y = 0; return a; }
ll x1, y1;
ll g = extgcd(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return g;
}
bool solveLinear(ll a, ll b, ll c, ll &x0, ll &y0, ll &g) {
g = extgcd(abs(a), abs(b), x0, y0);
if (c % g) return false;
x0 *= c / g;
y0 *= c / g;
if (a < 0) x0 = -x0;
if (b < 0) y0 = -y0;
return true;
}31 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
GCD, LCM & Extended GCD
Functions
General Solution for
Given one solution , all solutions:
for any integer .