Skip to content

Commit 7cbbd62

Browse files
committed
feat: implement while-loop optimization
1 parent 2091ea0 commit 7cbbd62

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Sum of multiples of 3 or 5 below 'limit'. Uses the while-loop accumulator
3+
* pattern and trial division. Iterates through multiples only.
4+
*
5+
* Time complexity: O(n)
6+
* Space complexity: O(1), the 64-bits IEEE 754 standard
7+
*
8+
* @param {number} limit Exclusive upper limit of the series.
9+
* @returns {number} Sum of multiples of 3 or 5 below 'limit'.
10+
*/
11+
const sumMultsOf3Or5 = (limit) => {
12+
const limitFloor = Math.floor(limit)
13+
let mult3 = 3
14+
let mult5 = 5
15+
let sum = 0
16+
17+
while (mult5 < limitFloor) {
18+
sum += mult3
19+
if (mult5 % 3 !== 0) sum += mult5 // Avoid counting multiples of both twice
20+
21+
mult3 += 3
22+
mult5 += 5
23+
}
24+
25+
while (mult3 < limitFloor) {
26+
sum += mult3
27+
mult3 += 3
28+
}
29+
30+
return sum
31+
}
32+
33+
module.exports = {
34+
fun: sumMultsOf3Or5,
35+
id: 'while-loop multiples-only'
36+
}
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
const solutions = [
22
require('./multiples-of-3-or-5-analytic'),
3-
require('./multiples-of-3-or-5-forloop-obo'),
4-
require('./multiples-of-3-or-5-reduce')
3+
require('./multiples-of-3-or-5-for-obo'),
4+
require('./multiples-of-3-or-5-reduce'),
5+
require('./multiples-of-3-or-5-while-mo')
56
]
67

78
module.exports = solutions

0 commit comments

Comments
 (0)