본문 바로가기
알고리즘/Codewars

[Codewars] Sum of odd numbers (7 kyu) / JavaScript

by fluss 2022. 12. 23.

https://www.codewars.com/kata/55fd2d567d94ac3bc9000064

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Given the triangle of consecutive odd numbers:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...

Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input --> Output)

1 -->  1
2 --> 3 + 5 = 8

 

설명:

연속된 홀수의 삼각형이 주어졌을 때:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...

이 삼각형의 n번째 줄의 합을 계산하세요(인덱스 1에서 시작). 예:(입력 --> 출력)

1 -->  1
2 --> 3 + 5 = 8
 
 

풀이

n번째 줄의 첫 번째 숫자는 n * (n - 1) + 1이고 마지막 숫자는 첫 번째 숫자에 (n - 1)을 더한 값이다. 가우스 공식으로 첫 번째 숫자부터 마지막 숫자까지 더한 값을 반환해 주었다.

 

코드

function rowSumOddNumbers(n) {
	const startN = n * (n - 1) + 1;
    const endN = startN + (n - 1) * 2;
    return (startN + endN) * n / 2;
}

 

다른 사람의 좋았던 풀이

function rowSumOddNumbers(n) {
  return Math.pow(n, 3);
}

댓글