File tree 2 files changed +39
-2
lines changed
algorithms-and-data-structures/project-euler/001-multiples-of-3-or-5
2 files changed +39
-2
lines changed Original file line number Diff line number Diff line change
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 number Diff line number Diff line change 1
1
const solutions = [
2
2
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' )
5
6
]
6
7
7
8
module . exports = solutions
You can’t perform that action at this time.
0 commit comments