CodeWars 코딩 문제 2021/08/26 - Sum of Square Numbers

이호현·2021년 8월 26일
0

Algorithm

목록 보기
134/138

[문제]

Given a non-negative integer c, decide whether there're two integers a and b such that a^2 + b^2 = c.

Example 1:

Input: c = 5
Output: true
Explanation: 1 1 + 2 2 = 5

Example 2:

Input: c = 3
Output: false

Example 3:

Input: c = 4
Output: true

Example 4:

Input: c = 2
Output: true

Example 5:

Input: c = 1
Output: true

(요약) 피타고라스의 정리가 되는지 아닌지를 판별하라.

[풀이]

var judgeSquareSum = function(c) {
  if(!c) return true;
   
  for(let i = 1, len = Math.sqrt(c); i <= len; i++) {
    const temp = c - (i * i);
       
    if(!((Math.sqrt(temp) * 10) % 10)) {
      return true;
    }
  }
   
  return false;
};

피타고라스의 정리는 두 정수의 제곱의 합이 다른 정수의 제곱의 합과 같다는 것이다.

주어진 수가 다른 두 정수의 제곱의 합으로 표현할 수 있는지만 확인하면 된다.

우선 0일 경우 truereturn해준다.

0이 아닐 경우 1부터 1씩 증가시키면서 제곱한 수를 주어진 수에서 빼고 나온 수가 곱근이 정수인지만 판별하면 된다.

profile
평생 개발자로 살고싶습니다

0개의 댓글

관련 채용 정보