LeetCode 2894: Divisible and Non-divisible Sums Difference
Problem Description
Explanation:
To solve this problem, we need to calculate two sums: the sum of numbers in the range [1, n] that are not divisible by m (num1
) and the sum of numbers in the same range that are divisible by m (num2
). The required answer is num1 - num2
.
-
Calculate
num1
:- For each number
i
in the range [1, n], ifi
is not divisible bym
, addi
tonum1
.
- For each number
-
Calculate
num2
:- Calculate the count of numbers in the range [1, n] that are divisible by
m
using the formulacount = n / m
. - The sum of all numbers divisible by
m
in the range [1, n] ism * count
, wherecount
is the number of multiples ofm
in the range [1, n].
- Calculate the count of numbers in the range [1, n] that are divisible by
-
Return the difference
num1 - num2
.
Time Complexity:
The time complexity of this solution is O(1) because we are performing a constant number of operations regardless of the input size.
Space Complexity:
The space complexity of this solution is O(1) as we are using a constant amount of extra space.
:
Solutions
class Solution {
public int subtractNonDivisible(int n, int m) {
int num1 = 0;
// Calculate num1
for (int i = 1; i <= n; i++) {
if (i % m != 0) {
num1 += i;
}
}
// Calculate num2
int count = n / m;
int num2 = m * count;
return num1 - num2;
}
}
Loading editor...