diff --git a/homework/nwd-nnw/nwdNww.hpp b/homework/nwd-nnw/nwdNww.hpp index 0491a2c9..6aeac72a 100644 --- a/homework/nwd-nnw/nwdNww.hpp +++ b/homework/nwd-nnw/nwdNww.hpp @@ -1,11 +1,23 @@ #pragma once int NWD(int lhs, int rhs) { - // TODO: Implement me :) - return -1; + int first = (lhs > 0) ? lhs : -lhs; + int second = (rhs > 0) ? rhs : -rhs; + + while (second != 0) { + int rest = 0; + rest = first % second; + first = second; + second = rest; + } + + return first; } int NWW(int lhs, int rhs) { - // TODO: Implement me :) - return -1; + if (lhs == 0 || rhs == 0) { + return 0; + } + int result = (lhs / NWD(lhs, rhs)) * rhs; // divide first to protect against overflow + return (lhs < 0 ^ rhs < 0) ? -result : result; }