Skip to content

Instantly share code, notes, and snippets.

@theevo
Created April 2, 2020 15:55
Show Gist options
  • Save theevo/e3787d282a37a466d94d31efd6806820 to your computer and use it in GitHub Desktop.
Save theevo/e3787d282a37a466d94d31efd6806820 to your computer and use it in GitHub Desktop.
//: [Palindrome](@previous)
/*:
# Thursday Stretch Problem 5.4
## Greatest Common Divisor
### Instructions
- Read about recursion.
- Note Google's little joke when you search recursion in Chrome.
- Create a function that returns the greatest common divisor of two numbers using recursion. (function calling itself).
*/
import Foundation
func greatestCommonDivisor(biggerNumber lhs: Int, smallerNumber rhs: Int) -> Int {
if rhs <= 0 || lhs <= 0 {
return 1
} else if lhs % rhs == 0 {
return rhs
} else {
print("\(rhs), \(lhs % rhs)")
return greatestCommonDivisor(biggerNumber: rhs, smallerNumber: lhs % rhs )
}
}
greatestCommonDivisor(biggerNumber: 20, smallerNumber: 15)
greatestCommonDivisor(biggerNumber: 20, smallerNumber: 0)
greatestCommonDivisor(biggerNumber: 1024, smallerNumber: 18)
greatestCommonDivisor(biggerNumber: 100, smallerNumber: 13)
// Euclid was a genius!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment