Last active
September 12, 2019 01:07
-
-
Save PaulWoodIII/ee405e182763841f4eb197e149131173 to your computer and use it in GitHub Desktop.
Three approaches to the same problem. I think the second is best for swift but I made the third for fun to display the algorithm as a stream, missing the first higher though...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func gcd_recursive(_ a: Int, _ b : Int) -> Int { | |
let higher = max(a, b) | |
let lower = min(a, b) | |
let r = higher % lower | |
if r == 0 { | |
return lower | |
} | |
return gcd_recursive(lower, r) | |
} | |
gcd_recursive(110, 25) | |
func gcd_loop(_ a : Int, _ b : Int) -> Int { | |
var higher = max(a, b) | |
var lower = min(a, b) | |
var r = higher % lower | |
while r != 0 { | |
higher = lower | |
lower = r | |
r = higher % lower | |
} | |
return lower | |
} | |
gcd_loop(110, 25) | |
func gcd_Generator(_ a: Int, _ b: Int) -> Int { | |
struct GCDStruct: Sequence, IteratorProtocol { | |
var higher: Int | |
var lower: Int | |
mutating func next() -> Int? { | |
if lower == 0 { | |
return nil | |
} else { | |
defer { | |
let r = higher % lower | |
higher = lower | |
lower = r | |
} | |
return lower | |
} | |
} | |
} | |
let generator = GCDStruct(higher: max(a, b), lower: min(a, b)) | |
let all = [Int](generator) | |
return all.last ?? 1 | |
} | |
gcd_Generator(110, 25) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment