diff --git a/plugins/builtin/romfs/lang/en_US.json b/plugins/builtin/romfs/lang/en_US.json index 3ecfbf689..85d06081e 100644 --- a/plugins/builtin/romfs/lang/en_US.json +++ b/plugins/builtin/romfs/lang/en_US.json @@ -579,6 +579,7 @@ "hex.builtin.tools.error": "Last error: '{0}'", "hex.builtin.tools.euclidean_algorithm": "Euclidean Algorithm", "hex.builtin.tools.euclidean_algorithm.description": "The Euclidean algorithm is an efficient method for computing the greatest common divisor (GCD) of two numbers, the largest number that divides both of them without leaving a remainder.\n\nBy extension, this also provides an efficient method for computing the least common multiple (LCM), the smallest number divisible by both.", + "hex.builtin.tools.euclidean_algorithm.overflow": "Overflow detected! Value of a and b are too large.", "hex.builtin.tools.file_tools": "File Tools", "hex.builtin.tools.file_tools.combiner": "Combiner", "hex.builtin.tools.file_tools.combiner.add": "Add...", diff --git a/plugins/builtin/source/content/tools_entries.cpp b/plugins/builtin/source/content/tools_entries.cpp index d789918e7..dafc7fc27 100644 --- a/plugins/builtin/source/content/tools_entries.cpp +++ b/plugins/builtin/source/content/tools_entries.cpp @@ -2070,11 +2070,12 @@ namespace hex::plugin::builtin { void drawEuclidianAlgorithm() { - static i64 a, b; + static u64 a, b; static i64 gcdResult = 0; static i64 lcmResult = 0; static i64 p = 0, q = 0; + static bool overflow = false; constexpr static auto extendedGcd = [](T a, T b) -> std::pair { T x = 1, y = 0; @@ -2101,10 +2102,23 @@ namespace hex::plugin::builtin { hasChanged = ImGui::InputScalar("A", ImGuiDataType_U64, &a) || hasChanged; hasChanged = ImGui::InputScalar("B", ImGuiDataType_U64, &b) || hasChanged; - if (hasChanged) { - gcdResult = std::gcd(a, b); - lcmResult = std::lcm(a, b); - std::tie(p, q) = extendedGcd(a, b); + // Detect overflow + const u64 multiplicationResult = a * b; + if (a != 0 && multiplicationResult / a != b) { + gcdResult = 0; + lcmResult = 0; + p = 0; + q = 0; + + overflow = true; + } else { + if (hasChanged) { + gcdResult = std::gcd(a, b); + lcmResult = std::lcm(a, b); + std::tie(p, q) = extendedGcd(a, b); + } + + overflow = false; } ImGui::Separator(); @@ -2122,6 +2136,11 @@ namespace hex::plugin::builtin { ImGui::EndBox(); } + if (overflow) + ImGui::TextColored(ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed), "hex.builtin.tools.euclidean_algorithm.overflow"_lang); + else + ImGui::NewLine(); + } }