알고리즘 5 - Grasshopper - Summation

tamagoyakii·2021년 10월 4일
1

알고리즘

목록 보기
5/89

Q.

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

A)

int summation(int num) {
  int ret = 0;
  for (int i = 1; i <= num; i++)
    ret += i;
  return ret;
}

return num * (num + 1) / 2;
이렇게 푸신 분들도 많더라,,, 분명 알고 있는 공식인데 보기 전에는 기억이 안났다ㅎㅎ
내 머리가 언제쯤 다시 팔팔 돌아가줄까? 열심히 굴러라~~

0개의 댓글