Skip to content

Instantly share code, notes, and snippets.

@nmbr73
Last active September 28, 2022 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmbr73/6418a2ba5c5b6b0bcd6e3f54eaa7e342 to your computer and use it in GitHub Desktop.
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
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