๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

Programmers Lv.1 : ์ •์ˆ˜ ์ œ๊ณฑ๊ทผ ํŒ๋ณ„

by Youcodein 2022. 11. 7.
728x90
๋ฐ˜์‘ํ˜•

Programmers Lv.1 : ์ •์ˆ˜ ์ œ๊ณฑ๊ทผ ํŒ๋ณ„

" ์ž„์˜์˜ ์–‘์˜ ์ •์ˆ˜ n์— ๋Œ€ํ•ด, n์ด ์–ด๋–ค ์–‘์˜ ์ •์ˆ˜ x์˜ ์ œ๊ณฑ์ธ์ง€ ์•„๋‹Œ์ง€ ํŒ๋‹จํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค. n์ด ์–‘์˜ ์ •์ˆ˜ x์˜ ์ œ๊ณฑ์ด๋ผ๋ฉด x+1์˜ ์ œ๊ณฑ์„ ๋ฆฌํ„ดํ•˜๊ณ , n์ด ์–‘์˜ ์ •์ˆ˜ x์˜ ์ œ๊ณฑ์ด ์•„๋‹ˆ๋ผ๋ฉด -1์„ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”. "

n์€ 1์ด์ƒ, 50000000000000 ์ดํ•˜์ธ ์–‘์˜ ์ •์ˆ˜์ž…๋‹ˆ๋‹ค.

๋‚ด ํ’€์ด

function solution(n) {
    if(Math.sqrt(n) % 1 !== 0){
        return -1;
    } else {
        return(Math.sqrt(n) + 1)*(Math.sqrt(n) + 1)
    }
}

์ œ๊ณฑ๊ทผ์˜ ๊ฐ’์ด 1๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋จธ์ง€๊ฐ€ ์žˆ์œผ๋ฉด ์–‘์˜ ์ •์ˆ˜ x์˜ ์ œ๊ณฑ์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— -1์„ ๋ฆฌํ„ดํ•˜๊ณ  ๊ทธ ์™ธ์—๋Š” x+1์„ ์ œ๊ณฑํ•œ๋‹ค.

๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ํ’€์ด

function solution(n) {
    var answer = 0;
  
    for(let i=0, a=0; i<=n; i++){
      if(n/i===i){
        a = i + 1
        return a*a
      } else {
        answer = -1
      }
    }
  
    return answer;
}
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€