Skip to content
Snippets Groups Projects
Commit b9f0e47b authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add Linear Diophantine Equation

parent 7c0e61f0
No related branches found
No related tags found
No related merge requests found
/// Extended Euclidean algorithm
///
/// Time: O(log n)
/// Time: O(log min(a,b))
/// Space: O(1)
struct ExtendedEuclidean {
......
/// Linear Diophantine Equation
///
/// Description:
/// A Linear Diophantine Equation is an equation in the form $ax + by = c$.
/// A solution of this equation is a pair $(x,y)$ that satisfies the equation.
/// The locus of (lattice) points whose coordinates $x$ and $y$ satisfy the
/// equation is a straigh line. \par
/// The equation has a solution only if $gcd(a,b) | c$. In the case of
/// existing a solution for the provided $a, b, c$, the infinite set of
/// coordinates $(x,y)$ can be obtained with get(t) for
/// $t=...,-2,-1,0,1,2,...$.
///
/// Time: O(log min(a,b))
/// Space: O(1)
struct Diophantine {
int a, b, c, d;
int x0, y0;
bool has_solution;
Diophantine(int a, int b, int c) :
a(a), b(b), c(c)
{ init(); }
void init() {
ExtendedEuclidean ext_gcd;
int w0, z0;
d = ext_gcd.run(a, b, w0, z0);
if (c % d == 0) {
x0 = w0 * (c / d);
y0 = z0 * (c / d);
has_solution = true;
} else {
has_solution = false;
}
}
ii get(int t) {
if (!has_solution) return ii(inf, inf);
return ii(x0 + t * (b / d), y0 - t * (a / d));
}
};
No preview for this file type
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment