Greatest Common Divisor
Easy math · number-theory
Description
Constraints
1 <= a, b
Examples
Input: a = 48, b = 36
Output: 12
Hints (1)
- Euclid: gcd(a, b) = gcd(b, a mod b).
Solutions
Euclidean algorithm. · Time O(log min(a,b)) · Space O(1)
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
Euclidean algorithm. · Time O(log min(a,b)) · Space O(1)
function gcd(a, b) {
while (b !== 0) { [a, b] = [b, a % b]; }
return a;
}
Euclidean algorithm. · Time O(log min(a,b)) · Space O(1)
function gcd($a, $b) {
while ($b !== 0) { $t = $b; $b = $a % $b; $a = $t; }
return $a;
}
Euclidean algorithm. · Time O(log min(a,b)) · Space O(1)
def gcd(a, b):
while b:
a, b = b, a % b
return a
Euclidean algorithm. · Time O(log min(a,b)) · Space O(1)
function gcd(a: number, b: number): number {
while (b !== 0) { [a, b] = [b, a % b]; }
return a;
}
Create a free account to submit solutions, track progress and save problems.
Create account