Juni_Dev_log

(200208_TIL) "Difference Of Squares" 본문

CodingTest/Exercism

(200208_TIL) "Difference Of Squares"

Juni_K 2021. 2. 8. 19:36

▶ Difference Of Squares

Difference Of Squares

📌 Problem

Introduction

Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.

: 합의 제곱과 처음 N 개의 자연수의 제곱의 합 사이의 차이를 찾으십시오.

The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.

: 1~10까지의 자연수들의 합의 제곱은 55² = 3025이다.

The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.

: 1~10까지의 자연수들의 제곱의 합은 385이다.

Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.

: 1~10까지의 자연수의 합의 제곱과 1~10까지의 자연수들의 제곱의 합의 차이는 3025 - 385 = 2640 ;

You are not expected to discover an efficient solution to this yourself from first principles; research is allowed, indeed, encouraged.

: 첫 원칙으로부터 너 스스로 효율적인 해결책을 발견하는 것을 기대할 수 없다. 실제로 연구가 허용되었다. 

Finding the best algorithm for the problem is a key skill in software engineering.

: 이 문제를 위한 최고의 알고리즘을 발견하는 것이 소프트엔지니어링에서 중요한 기술이다.

 

 

Tip) 

- 클래스의 생성자로 num을 전해준다.

- 받은 num 을 통해서 num 보다 작고 0보다 큰 배열을 만든다.

- 만들어진 배열을 통해서, 제곱의 합과 합의 제곱을 구한다.

 

 

💯 Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export class Squares {
  constructor(num) {
    this.num = num;
  }
 
  // 제곱의 합
  get sumOfSquares() {
    let sum = 0;
 
    for (let i = 1; i <= this.num; i++){
        sum += i** 2;
    }
 
    return sum;
  }
 
  // 합의 총합의 제곱
  get squareOfSum() {
    let sum = 0;
 
    for (let i = 1; i <= this.num; i++){
      sum += i;
    }
    return sum** 2;
  }
 
  // 합의 제곱 - 제곱의 합
  get difference() {
    return this.squareOfSum - this.sumOfSquares;
  }
}
 
cs

 

-  constructor 를 통해서 클래스와 함께 보내는 num을 받는다.

- 임의로 sum이라는 변수를 만들고 0으로 지정한다.

- for 문을 통해서, num 보다 작거나 같은 경우의 값을 구해서 sum에 더한다. (제곱의 합 : i ** 2 / 합의 제곱 : sum**2)

- 차이를 나타내는 함수는 두 함수의 값을 받아와서 빼면 된다.

'CodingTest > Exercism' 카테고리의 다른 글

(200211_TIL) "Anagram"  (0) 2021.02.11
(200209_TIL) "Perfect Numbers"  (0) 2021.02.09
(200207_TIL) 'Word Count'  (0) 2021.02.07
(200205_TIL) 'Raindrops'  (0) 2021.02.05
(200204_TIL) 'Hamming'  (0) 2021.02.04
Comments