GCD
Calculates the greatest common divisor between two or more numbers.
- Define a
gcd()function for two numbers, which uses recursion. - Base case is when
yequals0, which returnsx. - Otherwise the GCD of
yand the remainder of the divisionx/yis returned. - Use
gcd()andrangeto apply the calculation to all given numbers.
func gcd(x, y int) int {
if y == 0 {
return x
}
return gcd(y, x%y)
}
func GCD(nums ...int) int {
r := nums[0]
for _, num := range nums[1:] {
r = gcd(r, num)
}
return r
}GCD(8, 36) // 4
GCD([]int{12, 8, 32}...) // 4