2894. Divisible and Non-divisible Sums Difference
2894. Divisible and Non-divisible Sums Difference
Approach
Problem statement:
In , find the difference between the sum of all numbers not divisible by and the sum of all numbers divisible by .
Derivation:
-
Total sum:
-
Numbers divisible by :
-
Sum of non-divisible numbers:
-
The required answer:
Code
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
# divisible = m * (1 + n // m) * (n // m) // 2
# undivisible = n * (n + 1) // 2 - n * ((1 + n // m) * (n // m) // 2)
return - m * ((1 + n // m) * (n // m)) + (n * (n + 1) >> 1)const differenceOfSums = (n: number, m: number): number =>
-m * ((1 + Math.floor(n / m)) * Math.floor(n / m)) + ((n * (n + 1)) >> 1);贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
2679. Sum in a Matrix
LeetCode 2679. Sum in a Matrix — Sort each row, then use zip and max to find the column-wise maximums and sum them. For Python developers learning matrix traversal tricks.
2894. Divisible and Non-Divisible Sums Difference
LeetCode 2894. Divisible and Non-Divisible Sums Difference — direct mathematical solution using the arithmetic series formula to compute the sum of numbers divisible by m and those that are not in [1, n], then taking their difference. Suitable for job seekers and algorithm beginners working through easy math problems on LeetCode.