코딩테스트

프로그래머스 정수 제곱근 판별

다시은 2023. 12. 18. 09:52

 

 

 

 

제곱근/제곱 구하기

Double 형이나 Float 형이어야 한다.

import Kotlin.math.*

var a = 25
var answer = sqrt(a)

var answer2 = answer.pow(2)

 

 

 

 

첫 시도

import kotlin.math.*
class Solution {
    fun solution(n: Long): Long {
        var x = sqrt(n.toDouble()) 
        var answer : Long = 0
        if ( x > 0 ) {
            answer = (x + 1).pow(2).toLong()
        } else {
            answer = -1
        }      
        return answer
    }
}

제곱근이 양의 정수가 아닌 경우가 반환이 안된다.

왜 그럴까?

x 는 n 을 Double 형으로 변환한 다음 구한 제곱근이고

그 값이 0보다 클 때 x+1 의 제곱을 반환하도록 했다.

그러면 제곱근이 양의 정수가 아닌 경우

양수이지만 정수가 아닐 때도

-1 을 반환해야하는 건가?

지금 제곱근으로 나온 값은 Double 형이니 이게 Int 로 변환했을 때랑 값이 다른 걸로 구분해야 하나?

그런데 Double 과 Int 값 비교는 안된다.

그러니 구한 Double 형 x 를 1로 나눴을 때 0이 아니면 소수점을 가지고 있는 수이니 정수가 아닌 걸로 판단하고 조건문에 넣어봤다. 

 

import kotlin.math.*

class Solution {
    fun solution(n: Long): Long {
        var x = sqrt(n.toDouble()) 
        var answer : Long = 0
        if ( x % 1 != 0.0 ) {
            answer = -1
        } else {
            answer = (x + 1).pow(2).toLong()
        }

 

 

 

다른 사람 풀이

class Solution {
   fun solution(n: Long): Long {
        for (i in 0..n) {
            if (i * i == n) {
                return ((i + 1) * (i + 1))
            }
        }
        return -1
    }
}

 

for 문에 넣어볼 생각을 못했다

 

 

class Solution {
    fun solution(n: Long): Long {
        val x = sqrt(n.toDouble())
        return (if (x == floor(x)) ((x + 1) * (x + 1)).toLong() else -1L)
    }
}

 

floor 내림을 통해 간단하게 비교했다

 

 

 

12/19 다시 풀어보기

class Solution {
    fun solution(n: Long): Long {
      
        for(i in 1..n){
          if (i * i == n) return (i+1)*(i+1).toLong() 
      }
        
        return -1L
    }
}

제곱근 구할 때는 Double 이나 Float 이어야 한다!!!!1