Problem
- Write a program that finds the summation of every number from 1 to n.
- The n will always be a positive integer greater than 0.
Solution 01
function summation(n) {
let sum = 0;
for (let i = 0; i <= n; i++) {
sum += i;
}
return sum;
}
summation(4); // 10
summation(10); // 55
summation(100); // 5050
Solution 02
function summation(n) {
return (1 + n) * (n / 2);
}
summation(4); // 10
summation(10); // 55
summation(100); // 5050
Solution 03
function summation(n) {
return ((1 + n) * n) / 2;
}
summation(4); // 10
summation(10); // 55
summation(100); // 5050
Solution 04
function summation(n) {
if (n <= 1) {
return 1;
} else {
return n + summation(n - 1);
}
}
summation(4); // 10
summation(10); // 55
summation(100); // 5050