checkpoint 4: find Square root

그루두·2024년 4월 15일
0

100 days of SwiftUI

목록 보기
12/108

100 days of swiftui: checkpoint 4
https://www.hackingwithswift.com/quick-start/beginners/checkpoint-4

challenge

Write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. That sounds easy, but there are some catches:

  1. You can’t use Swift’s built-in sqrt() function or similar – you need to find the square root yourself.
  2. If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error.
  3. You should only consider integer square roots – don’t worry about the square root of 3 being 1.732, for example.
  4. If you can’t find the square root, throw a “no root” error.

As a reminder, if you have number X, the square root of X will be another number that, when multiplied by itself, gives X. So, the square root of 9 is 3, because 3x3 is 9, and the square root of 25 is 5, because 5x5 is 25.

solution

enum CalculateError: Error {
    case outOfBound, notInteger
}

func findSqrt(num: Int) throws -> Int {
    if num > 10000 || num < 1 {
        throw CalculateError.outOfBound
    } else {
        for i in 1...100 {
            if i * i == num {
                return i
            }
        }
        throw CalculateError.notInteger
    }
}

let num = 3

do {
    let result = try findSqrt(num: num)
    print("\(result) is the square root of \(num)!")
} catch CalculateError.outOfBound {
    print("The number is out of bound!")
} catch CalculateError.notInteger {
    print("The result is not an integer!")
} catch {
    print("no root")
}

1부터 10,000까지 중 한 숫자의 루트를 찾는 것이기에, 루트를 찾을 때 반복문으로 1(1의 루트)부터 100(10,000의 루트)까지만 확인한다. 그리고 이외에 숫자가 설정한 범위를 벗어나거나 루트 값이 정수가 아니면 에러를 발생하도록 설정했다.

코드 파일
https://github.com/soaringwave/Ios-studying/blob/main/findSqrt.playground/Contents.swift

profile
계속 해보자

0개의 댓글

관련 채용 정보