LeetCode 题解工作台
倍数求和
给你一个正整数 n ,请你计算在 [1,n] 范围内能被 3 、 5 、 7 整除的所有整数之和。 返回一个整数,用于表示给定范围内所有满足约束条件的数字之和。 示例 1: 输入: n = 7 输出: 21 解释: 在 [1, 7] 范围内能被 3 、 5 、 7 整除的所有整数分别是 3 、 5 …
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们直接枚举 中的每一个数 ,如果 能被 , , 整除,那么就将 累加到答案中。 枚举结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你一个正整数 n ,请你计算在 [1,n] 范围内能被 3、5、7 整除的所有整数之和。
返回一个整数,用于表示给定范围内所有满足约束条件的数字之和。
示例 1:
输入:n = 7 输出:21 解释:在[1, 7]范围内能被3、5、7整除的所有整数分别是3、5、6、7。数字之和为21。
示例 2:
输入:n = 10 输出:40 解释:在[1, 10]范围内能被3、5、7整除的所有整数分别是3、5、6、7、9、10。数字之和为40。
示例 3:
输入:n = 9 输出:30 解释:在[1, 9]范围内能被3、5、7整除的所有整数分别是3、5、6、7、9。数字之和为30。
提示:
- 1 <= n <= 103
解题思路
方法一:枚举
我们直接枚举 中的每一个数 ,如果 能被 , , 整除,那么就将 累加到答案中。
枚举结束后,返回答案即可。
时间复杂度 ,其中 为题目给定的整数。空间复杂度 。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looks for understanding of basic divisibility rules.
- question_mark
Evaluates ability to optimize solutions using mathematical principles.
- question_mark
Assesses familiarity with inclusion-exclusion in combinatorics.
常见陷阱
外企场景- error
Overcomplicating the solution with unnecessary loops.
- error
Failing to account for duplicates when using the mathematical summation approach.
- error
Using an inefficient brute force solution for larger inputs.
进阶变体
外企场景- arrow_right_alt
Consider adding additional divisors, such as 11 or 13, to test understanding of the inclusion-exclusion principle.
- arrow_right_alt
Change the range to [1, n^2] for larger n values and examine time complexity.
- arrow_right_alt
Add constraints that n can be as large as 10^6 and explore more efficient algorithms.