From 684b6483c1a8f9af199d975f11deda7c6c39821c Mon Sep 17 00:00:00 2001 From: iagorrr04 Date: Sat, 10 Feb 2024 18:53:29 -0300 Subject: [PATCH] :sparkles: adds algorithm to find diophantine equation solutions --- .../find-solution-diophantine-equation.cpp | 25 +++++++++++++++++++ .../find-solution-diophantine-equation.tex | 5 ++++ 2 files changed, 30 insertions(+) create mode 100644 algorithms/math/find-solution-diophantine-equation.cpp create mode 100644 algorithms/math/find-solution-diophantine-equation.tex diff --git a/algorithms/math/find-solution-diophantine-equation.cpp b/algorithms/math/find-solution-diophantine-equation.cpp new file mode 100644 index 00000000..4640ffaf --- /dev/null +++ b/algorithms/math/find-solution-diophantine-equation.cpp @@ -0,0 +1,25 @@ +ll gcd(ll a, ll b, ll &x, ll &y) { + if (b == 0) { + x = 1; + y = 0; + return a; + } + ll x1, y1; + ll d = gcd(b, a % b, x1, y1); + x = y1; + y = x1 - y1 * (a / b); + return d; +} + +bool find_any_solution(ll a, ll b, ll c, ll &x0, ll &y0) { + auto g = gcd(a < 0 ? -a : a, b < 0 ? -b : 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; +} diff --git a/algorithms/math/find-solution-diophantine-equation.tex b/algorithms/math/find-solution-diophantine-equation.tex new file mode 100644 index 00000000..38a60b78 --- /dev/null +++ b/algorithms/math/find-solution-diophantine-equation.tex @@ -0,0 +1,5 @@ +\subsection{Linear Diophantine Equation: Find any solution} + +Given $a$ $b$, $c$ finds the solution to the equation $ax + by = c$, the result will be stored in the reference variables $x0$ and $y0$ + +time: $O(\log{min(a,b)})$