코드로 우주평화

Grasshopper - Summation 본문

나는 이렇게 학습한다/Algorithm & SQL

Grasshopper - Summation

daco2020 2022. 3. 3. 02:08
반응형

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

 

 

Solution

1. Repeat the number incrementing by 1 as much as 'num'.
2. Add up all the calculated numbers and return them.

 

 

 

JS code ::

// js :: for

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

 

 

 

Python code ::

# python :: range, sum
def summation(num):
    return sum(range(num + 1))

 

# python :: recursive function, ternary operator
def summation(num):
    return 0 if num <= 0 else num + summation(num-1)​

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Is this a triangle?  (0) 2022.03.04
Sum of Numbers  (0) 2022.03.03
Counting Duplicates  (0) 2022.03.01
Growth of a Population  (0) 2022.03.01
Binary Addition  (0) 2022.02.27