#2652
Sum Multiples
EasyMathArithmetic SeriesMathematical Summation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of checking each number individually, we can calculate the sum of multiples of 3, 5, and 7 directly using the formula for the sum of an arithmetic series. This is much faster and avoids unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Define a helper function to calculate the sum of multiples of a number 'x' up to 'n'.
- 2Step 2: Use the formula sum = x * (k * (k + 1)) / 2, where k = n // x.
- 3Step 3: Calculate the sum for 3, 5, and 7, and subtract the sums for their least common multiples (15, 21, 35) to avoid double counting.
- 4Step 4: Return the total sum.
solution.py9 lines
1# Full working Python code
2
3def sum_of_multiples(x, n):
4 k = n // x
5 return x * k * (k + 1) // 2
6
7def sum_multiples(n):
8 return (sum_of_multiples(3, n) + sum_of_multiples(5, n) + sum_of_multiples(7, n) -
9 sum_of_multiples(15, n) - sum_of_multiples(21, n) - sum_of_multiples(35, n))ℹ
Complexity note: The time complexity is O(1) because we are performing a constant number of calculations regardless of the size of n. The space complexity is O(1) as we are using a fixed amount of space for our variables.
- 1Understanding how to avoid double counting when summing multiples of multiple numbers is crucial.
- 2Using arithmetic series formulas can drastically reduce computation time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.