1
0
mirror of synced 2024-11-28 09:30:51 +01:00

impr: Detect overflow in Euclidean algorithm tool

This commit is contained in:
WerWolv 2023-11-08 12:40:33 +01:00
parent 87e7f817c1
commit ea5d4ca3ae
2 changed files with 25 additions and 5 deletions

View File

@ -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...",

View File

@ -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 = []<typename T>(T a, T b) -> std::pair<T, T> {
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<i128, i128>(a, b);
lcmResult = std::lcm<i128, i128>(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();
}
}