GCD & LCM STL¶ cppreference Head FilesC++ Versionstd::gcdstd::lcm #include <numeric> -std=c++17 template< class M, class N > constexpr std::common_type_t<M, N> gcd( M m, N n ); template< class M, class N > constexpr std::common_type_t<M, N> lcm( M m, N n ); GCD 1¶ Conditional OperatorBitwise Operation int gcd(int x, int y) { return y>0 ? gcd(y, x%y) : x; } int gcd(int x, int y) { while (y^=x^=y^=x%=y); return x; } LCM 2¶ int lcm(int x, int y) { return a / gcd(x, y) * y; } Tips Performing division before multiplication can help avoid overflow. Greatest Common Divisor ↩ Least Common Multiple ↩ Comments