LeetCode 题解工作台

倍数求和

给你一个正整数 n ,请你计算在 [1,n] 范围内能被 3 、 5 、 7 整除的所有整数之和。 返回一个整数,用于表示给定范围内所有满足约束条件的数字之和。 示例 1: 输入: n = 7 输出: 21 解释: 在 [1, 7] 范围内能被 3 、 5 、 7 整除的所有整数分别是 3 、 5 …

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们直接枚举 中的每一个数 ,如果 能被 , , 整除,那么就将 累加到答案中。 枚举结束后,返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 n ,请你计算在 [1,n] 范围内能被 357 整除的所有整数之和。

返回一个整数,用于表示给定范围内所有满足约束条件的数字之和。

 

示例 1:

输入:n = 7
输出:21
解释:[1, 7] 范围内能被 357 整除的所有整数分别是 3567 。数字之和为 21

示例 2:

输入:n = 10
输出:40
解释:[1, 10] 范围内能被 357 整除的所有整数分别是 3567910 。数字之和为 40

示例 3:

输入:n = 9
输出:30
解释:[1, 9] 范围内能被 357 整除的所有整数分别是 35679 。数字之和为 30

提示:

  • 1 <= n <= 103
lightbulb

解题思路

方法一:枚举

我们直接枚举 [1,..n][1,..n] 中的每一个数 xx,如果 xx 能被 33, 55, 77 整除,那么就将 xx 累加到答案中。

枚举结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nn 为题目给定的整数。空间复杂度 O(1)O(1)

1
2
3
4
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

倍数求和题解:数学·driven | LeetCode #2652 简单