-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
sum-of-a-sequence.js
82 lines (68 loc) · 1.92 KB
/
sum-of-a-sequence.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function sequenceSum(begin, end, step) {
if (begin > end) {
return 0;
}
// place to store the sum - initialized to begin value
let sum = begin;
// current sequence value - initialized to begin value
let currentValue = begin;
// while current sequence value is not equal to end
while (currentValue < end) {
// increment the sequence value by step
currentValue += step;
if (currentValue > end) {
break;
}
// add the new sequence value to sum
sum += currentValue;
}
return sum;
};
function sequenceSum(begin, end, step) {
if (begin > end) {
return 0;
}
let sum = 0;
let currentValue = begin;
while (currentValue <= end) {
sum += currentValue;
currentValue += step;
}
return sum;
};
function sequenceSum(begin, end, step) {
let sum = 0;
for (let i = begin; i <= end; i += step) {
sum += i;
}
return sum;
};
// arithmetic sum formula: n/2*(first term + last term) where n = number of terms
function sequenceSum(begin, end, step) {
if (begin > end) return 0;
const count = Math.floor((end - begin) / step) + 1;
return count * (begin + step * (count - 1) / 2);
}
function sequenceSum(begin, end, step) {
const length = Math.floor((end - begin) / step) + 1;
return Array
.from({ length }, (_, i) => begin + (step * i))
.reduce((sum, val) => sum + val, 0);
};
function sequenceSum(begin, end, step) {
const length = Math.floor((end - begin) / step) + 1;
return Array.from({ length })
.reduce((sum, _, i) => sum + (begin + (step * i)), 0);
};
function sequenceSum(begin, end, step) {
const length = Math.floor((end - begin) / step) + 1;
return Array.from({ length }, function(_, i) {
return begin + (step * i);
}).reduce(function(sum, val) {
return sum + val;
}, 0);
};
console.log(sequenceSum(2, 6, 2), 12);
console.log(sequenceSum(1, 5, 1), 15);
console.log(sequenceSum(1, 5, 3), 5);
console.log(sequenceSum(5, 1, 3), 0);