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 {
if (a < 0) {
func gcd(var a: Int, var b: Int) -> Int {
a = -a
}
if (b < 0) {
b = -b
}
if (b > a) {
( a, b ) = ( b, a )
}
while (true) {
a = abs(a); b = abs(b)
a %= b
if (a == 0) {
if (b > a) { swap(&a, &b) }

return b
}
while (b > 0) { (a, b) = (b, a % b) }
b %= a
return a
if (b == 0) {
return a
}
}
}
}


// Recursive
// Recursive

func gcd_rec(a:Int, b:Int) -> Int {
if (b != 0) {
func gcdr (var a: Int, var b: Int) -> Int {
return gcd_rec(b, a % b)
} else {
a = abs(a)
return abs(a)
b = abs(b)

}
if (b > a) { swap(&a, &b) }
return gcd_rec(a,b)
}


private func gcd_rec(a: Int, b: Int) -> Int {
return b == 0 ? a : gcd_rec(b, a % 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}}==