Home > katas > Grasshopper - Summation (8kyu) [TypeScript]
Grasshopper - Summation (8kyu) [TypeScript]
Chek kata on Codewars
Description:
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
Let's start with loop
solutions.
export const summation = (num: number) => {
let sum: number = 0
for(let i = 0; i <= num; i++) {
sum += i
}
return sum
}
Solution 2
Let's solve it with Gauss Formula
.
export const summation = (num: number) => num * (num + 1) / 2
Solution 3
Let's solve it with recursion
.
export const summation = (num: number) => {
return num ? num + summation(num - 1) : num
}