2894. Divisible and Non-Divisible Sums Difference
2894. Divisible and Non-Divisible Sums Difference
Thought
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 are:
-
Therefore the sum of non-divisible numbers is:
-
The answer is:
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
2894. Divisible and Non-divisible Sums Difference
LeetCode 2894. Divisible and Non-divisible Sums Difference — O(1) math solution using arithmetic series formulas to compute the difference without loops, ideal for beginners learning number theory.
3072. Distribute Elements into Two Arrays II
LeetCode 3072. Distribute Elements into Two Arrays II — Use Fenwick tree for O(n log n) counting of greater elements; reverse array and process from left to right, applying tie-breaking rules to distribute into two arrays. For intermediate learners.