Skip to content
Exercise · Functions · lesson 11 of 11

Exercise: GCD and LCM

Write two functions: int gcd(int a, int b) returns the greatest common divisor of the numbers, and int lcm(int a, int b) returns their least common multiple.

  • gcd(12, 18) → 6
  • gcd(0, 5) → 5
  • lcm(4, 6) → 12

Constraints: the numbers are non-negative; in gcd at least one of them is greater than zero, and in lcm both are. The result of lcm fits in an int, but the product a * b may not.

gcd.cpp — cpp
cpp · 8 lines
Ctrl+Enter run · Esc leave editor