EasyNo. 2652

Sum Multiples — LeetCode 2652 Python Solution

Topics
Math
Reading time
2 min

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

PythonSolution
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

Time
O(n)where n is the given integer
Space · auxiliary
O(1)

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.