Last active
September 28, 2022 09:10
-
-
Save nmbr73/6418a2ba5c5b6b0bcd6e3f54eaa7e342 to your computer and use it in GitHub Desktop.
Day 8, Checkpoint 4 of #100DaysOfSwiftUI ... #HACKINGWITHSWIFT https://www.hackingwithswift.com/quick-start/beginners/checkpoint-4
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
enum IntegerSqrtError : Error { | |
case outOfBounds, noRoot | |
} | |
func isqrt(_ n: Int) throws -> Int { | |
if n < 1 || n > 10_000 { | |
throw IntegerSqrtError.outOfBounds | |
} | |
for i in 1...100 { | |
if i*i == n { | |
return i | |
} | |
} | |
throw IntegerSqrtError.noRoot | |
} | |
for n in [-1,0,1,2,4,5,6,9,16,20,25,999,10_000,10_001] { | |
print("\(n):") | |
do { | |
print(" isqrt(\(n))=\(try isqrt(n))") | |
} catch IntegerSqrtError.outOfBounds { | |
print(" number out of bounds error") | |
} catch IntegerSqrtError.noRoot { | |
print(" no int sqrt for the given number") | |
} catch { | |
print(" an error occured") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment