Algorithm 8 - Grasshopper - Summation

Beast from the east·2021년 10월 6일
0

Algorithm

목록 보기
8/27

Q.

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

A)

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

another solution
int summation(int num) {
  return num * (num + 1) / 2;
} -> ex: num = 10 / (10 * 11) / 2 = 55 / 가우스 공식.
profile
Hello, Rabbit

0개의 댓글