1
0
mirror of synced 2024-11-28 17:40:51 +01:00

feat: Added extended Euclidean algorithm to tools

This commit is contained in:
WerWolv 2023-11-08 11:54:57 +01:00
parent 3af1840c6a
commit 87e7f817c1

View File

@ -2070,21 +2070,28 @@ namespace hex::plugin::builtin {
void drawEuclidianAlgorithm() { void drawEuclidianAlgorithm() {
static u64 a, b; static i64 a, b;
constexpr static auto gcd = [](u64 a, u64 b) { static i64 gcdResult = 0;
while (b != 0) { static i64 lcmResult = 0;
u64 temp = b; static i64 p = 0, q = 0;
b = a % b;
a = temp; constexpr static auto extendedGcd = []<typename T>(T a, T b) -> std::pair<T, T> {
T x = 1, y = 0;
T xLast = 0, yLast = 1;
while (b > 0) {
T quotient = a / b;
std::tie(x, xLast) = std::tuple { xLast, x - quotient * xLast };
std::tie(y, yLast) = std::tuple { yLast, y - quotient * yLast };
std::tie(a, b) = std::tuple { b, a - quotient * b };
} }
return a; return { x, y };
}; };
static u64 gcdResult = 0;
static u64 lcmResult = 0;
ImGui::TextFormattedWrapped("{}", "hex.builtin.tools.euclidean_algorithm.description"_lang); ImGui::TextFormattedWrapped("{}", "hex.builtin.tools.euclidean_algorithm.description"_lang);
ImGui::NewLine(); ImGui::NewLine();
@ -2095,19 +2102,21 @@ namespace hex::plugin::builtin {
hasChanged = ImGui::InputScalar("B", ImGuiDataType_U64, &b) || hasChanged; hasChanged = ImGui::InputScalar("B", ImGuiDataType_U64, &b) || hasChanged;
if (hasChanged) { if (hasChanged) {
gcdResult = gcd(a, b); gcdResult = std::gcd(a, b);
lcmResult = std::lcm(a, b);
if (gcdResult == 0) std::tie(p, q) = extendedGcd(a, b);
lcmResult = 0;
else
lcmResult = (a * b) / gcdResult;
} }
ImGui::Separator(); ImGui::Separator();
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().DisabledAlpha); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().DisabledAlpha);
ImGui::InputScalar("gcd(A, B)", ImGuiDataType_U64, &gcdResult, nullptr, nullptr, "%llu", ImGuiInputTextFlags_ReadOnly); ImGui::InputScalar("gcd(A, B)", ImGuiDataType_S64, &gcdResult, nullptr, nullptr, "%llu", ImGuiInputTextFlags_ReadOnly);
ImGui::InputScalar("lcm(A, B)", ImGuiDataType_U64, &lcmResult, nullptr, nullptr, "%llu", ImGuiInputTextFlags_ReadOnly);
ImGui::Indent();
ImGui::TextFormatted(ICON_VS_ARROW_RIGHT " a \u00D7 p + b \u00D7 q = ({0}) \u00D7 ({1}) + ({2}) \u00D7 ({3})", a, p, b, q);
ImGui::Unindent();
ImGui::InputScalar("lcm(A, B)", ImGuiDataType_S64, &lcmResult, nullptr, nullptr, "%llu", ImGuiInputTextFlags_ReadOnly);
ImGui::PopStyleVar(); ImGui::PopStyleVar();
ImGui::EndBox(); ImGui::EndBox();