倍数求和
难度:
标签:
题目描述
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 1:
Input: n = 7 Output: 21 Explanation: Numbers in the range[1, 7]
that are divisible by3
,5,
or7
are3, 5, 6, 7
. The sum of these numbers is21
.
Example 2:
Input: n = 10 Output: 40 Explanation: Numbers in the range[1, 10] that are
divisible by3
,5,
or7
are3, 5, 6, 7, 9, 10
. The sum of these numbers is 40.
Example 3:
Input: n = 9 Output: 30 Explanation: Numbers in the range[1, 9]
that are divisible by3
,5
, or7
are3, 5, 6, 7, 9
. The sum of these numbers is30
.
Constraints:
1 <= n <= 103
代码结果
运行时间: 26 ms, 内存: 16.0 MB
/*
* 思路:
* 使用 Java Stream API 来简化代码。
* 利用 IntStream.rangeClosed 生成 1 到 n 的数字流,
* 然后使用 filter 过滤能被 3、5、7 整除的数字,
* 最后使用 sum 汇总结果。
*/
import java.util.stream.IntStream;
public class Solution {
public int sumOfDivisibles(int n) {
return IntStream.rangeClosed(1, n)
.filter(i -> i % 3 == 0 || i % 5 == 0 || i % 7 == 0)
.sum();
}
}
解释
方法:
该题解使用了容斥原理。首先计算1到n之间能被3、5、7分别整除的数字之和,然后减去能同时被3和5、3和7、5和7整除的数字之和,最后加上能同时被3、5和7整除的数字之和。对于每个因子,使用等差数列求和公式计算能被该因子整除的数字之和。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
在使用容斥原理处理这个问题时,你是如何确定同时被3、5、7整除的数字之和需要加回来的?
▷🦆
为什么在计算能被多个数同时整除的数字时,需要使用负号(如(15, -1))?
▷🦆
在计算能被单个数字整除的数字之和时,为什么选择使用等差数列求和公式?
▷🦆
列表推导式中的(n // num) * (n // num + 1) * num * sign // 2是如何推导出来的?
▷