Description
- Write a program that finds the summation of every number from 1 to n.
- The number will always be a positive integer greater than 0.
Solution 01
function summation(n) {
let result = 0;
for (let i = 0; i <= n; i++) {
result += i;
}
return result;
}
summation(1); // 1
summation(2); // 3 (1 + 2)
summation(3); // 6 (1 + 2 + 3)
summation(4); // 10 (1 + 2 + 3 + 4)
Solution 02
function summation(n) {
return (n * (n + 1)) / 2;
}
summation(1); // 1
summation(2); // 3 (1 + 2)
summation(3); // 6 (1 + 2 + 3)
summation(4); // 10 (1 + 2 + 3 + 4)
Solution 03
function summation(n) {
return n ? n + summation(n - 1) : 0;
}
summation(1); // 1
summation(2); // 3 (1 + 2)
summation(3); // 6 (1 + 2 + 3)
summation(4); // 10 (1 + 2 + 3 + 4)
Solution 04
function summation(n) {
return [...Array(n)].reduce((result, i, index) => result + index + 1, 0);
}
summation(1); // 1
summation(2); // 3 (1 + 2)
summation(3); // 6 (1 + 2 + 3)
summation(4); // 10 (1 + 2 + 3 + 4)