Created
April 2, 2020 15:55
-
-
Save theevo/4f70217d8114a35fa61fd34f6f0c1805 to your computer and use it in GitHub Desktop.
This file contains 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
//: [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