Greatest common divisor: Difference between revisions
Content added Content deleted
Line 3,347: | Line 3,347: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
<lang Swift>// Iterative |
<lang Swift>// Iterative |
||
⚫ | |||
func gcd(var a: Int, var b: Int) -> Int { |
|||
a = -a |
|||
⚫ | |||
⚫ | |||
b = -b |
|||
⚫ | |||
if (b > a) { |
|||
⚫ | |||
⚫ | |||
a = abs(a); b = abs(b) |
|||
if (b > a) { swap(&a, &b) } |
|||
⚫ | |||
} |
while (b > 0) { (a, b) = (b, a % b) } |
||
⚫ | |||
if (b == 0) { |
|||
return a |
|||
⚫ | |||
} |
|||
} |
} |
||
// Recursive |
// Recursive |
||
func gcd_rec(a:Int, b:Int) -> Int { |
|||
func gcdr (var a: Int, var b: Int) -> Int { |
|||
⚫ | |||
⚫ | |||
a = abs(a) |
|||
b = abs(b) |
|||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
for (a,b) in [(1,1), (100, -10), (10, -100), (-36, -17), (27, 18), (30, -42)] { |
|||
⚫ | |||
println("Iterative: GCD of \(a) and \(b) is \(gcd(a, b))") |
|||
println("Recursive: GCD of \(a) and \(b) is \(gcdr(a, b))") |
|||
}</lang> |
}</lang> |
||
{{out}} |
|||
<pre> |
|||
Iterative: GCD of 1 and 1 is 1 |
|||
Recursive: GCD of 1 and 1 is 1 |
|||
Iterative: GCD of 100 and -10 is 10 |
|||
Recursive: GCD of 100 and -10 is 10 |
|||
Iterative: GCD of 10 and -100 is 10 |
|||
Recursive: GCD of 10 and -100 is 10 |
|||
Iterative: GCD of -36 and -17 is 1 |
|||
Recursive: GCD of -36 and -17 is 1 |
|||
Iterative: GCD of 27 and 18 is 9 |
|||
Recursive: GCD of 27 and 18 is 9 |
|||
Iterative: GCD of 30 and -42 is 6 |
|||
Recursive: GCD of 30 and -42 is 6 |
|||
</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |