알고리즘/Programmers

[Swift_Programmes] 정수 제곱근 판별

YEN_ 2023. 11. 21. 09:56

 

프로그래머스 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/12934


풀이    

import Foundation

func solution(_ n:Int64) -> Int64 {
    let value = Int64(sqrt(Double(n)))
    return value*value == n ? (value+1)*(value+1) : -1
}

문제 

더보기

임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.

 

중요 개념    

  • 제곱근 메소드를 사용해서 체크해주는게 우선이다 -> sqrt() 사용
    • sqrt() 는 반드시 Double이나 Float 형을 사용해서 계산해야 한다

 

https://developer.apple.com/documentation/accelerate/vforce/3241302-sqrt/

 

sqrt(_:) | Apple Developer Documentation

Returns the square root of each element in a vector of double-precision values.

developer.apple.com