Skip to content

Commit 77fda9d

Browse files
authored
Create sum-multiples.cpp
1 parent 5c75bc3 commit 77fda9d

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

C++/sum-multiples.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
// math, principle of inclusion and exclusion
5+
class Solution {
6+
public:
7+
int sumOfMultiples(int n) {
8+
const auto& f = [&](int d) {
9+
return d * (1 + (n / d)) * (n / d) / 2;
10+
};
11+
12+
return (f(3) + f(5) + f(7)) - (f(3 * 5) + f(5 * 7) + f(7 * 3)) + f(3 * 5 * 7);
13+
}
14+
};

0 commit comments

Comments
 (0)