Created
November 15, 2022 04:03
-
-
Save EvolvingParty/76d1ecb9e3d66831e2f2eb37e4943016 to your computer and use it in GitHub Desktop.
Day 8: 100 Days of SwiftUI – Hacking with Swift. 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
import Cocoa | |
///Write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. | |
///You can’t use Swift’s built-in sqrt() function or similar – you need to find the square root yourself. | |
///If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error. | |
///You should only consider integer square roots – don’t worry about the square root of 3 being 1.732, for example. | |
///If you can’t find the square root, throw a “no root” error. | |
enum isqrError: Error { | |
case noRoot, outOfBounds | |
} | |
func returnIntegerSquareRoot(for number: Int) throws -> String { | |
if number < 1 || number > 10_000 { | |
throw isqrError.outOfBounds | |
} | |
//To find a sqare root of a number without using sqrt(), find out which whole number, multiplied by itsself, returns the number. | |
//e.g sqrt of 25 is 5 because 5x5=25 | |
for i in 1...100 { | |
if number == i * i { | |
return "The square root of \(number) is \(i)" | |
} | |
} | |
throw isqrError.noRoot | |
} | |
for i in 0...10_001 { | |
do { | |
let answer = try returnIntegerSquareRoot(for: i) | |
print(answer) | |
} catch { | |
print(error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment