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

[Codewars] Grasshopper - Summation (8 kyu) / JavaScript

by fluss 2022. 12. 8.

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

 

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:

Summation

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:

summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
 
 

설명:

합계

1부터 num까지의 합을 찾는 프로그램을 작성하세요. 숫자는 언제나 0보다 큰 양의 정수입니다.

예:

summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
 

풀이

반복문으로 1부터 주어진 num까지의 합을 구해서 반환했다.

 

코드

var summation = function (num) {
  let sum = 0;
  for(let i = 1; i <= num; i++){
    sum += i;
  }
  return sum;
}

댓글