Sum Multiples — LeetCode 2652 Python Solution
- Problem
- #2652
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a positive integer n, find the sum of all integers in the range [1, n] inclusive that are divisible by 3, 5, or 7. Return an integer denoting the sum of all numbers in the given range satisfying the constraint.
Example
- Input
- n = 7
- Output
- 21
- Explanation
- Numbers in the range [1, 7] that are divisible by 3, 5, or 7 are 3, 5, 6, 7. The sum of these numbers is 21.
Python solution
class Solution:
def sumOfMultiples(self, n: int) -> int:
return sum(x for x in range(1, n + 1) if x % 3 == 0 or x % 5 == 0 or x % 7 == 0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the given integer |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2652. Sum Multiples is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2652. Sum Multiples?
- LeetCode 2652. Sum Multiples is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2652. Sum Multiples?
- The Python solution on this page runs in O(n), where n is the given integer.
- What is the space complexity of LeetCode 2652. Sum Multiples?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2652. Sum Multiples cover?
- LeetCode 2652. Sum Multiples is tagged Math on LeetCode.