LeetCode 2894: Divisible and Non-divisible Sums Difference Solution
Master LeetCode problem 2894 (Divisible and Non-divisible Sums Difference), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2894. Divisible and Non-divisible Sums Difference
Problem Explanation
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
iin the range [1, n], ifiis not divisible bym, additonum1.
- For each number
-
Calculate
num2:- Calculate the count of numbers in the range [1, n] that are divisible by
musing the formulacount = n / m. - The sum of all numbers divisible by
min the range [1, n] ism * count, wherecountis the number of multiples ofmin 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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2894 (Divisible and Non-divisible Sums Difference)?
This page provides optimized solutions for LeetCode problem 2894 (Divisible and Non-divisible Sums Difference) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2894 (Divisible and Non-divisible Sums Difference)?
The time complexity for LeetCode 2894 (Divisible and Non-divisible Sums Difference) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2894 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2894 in Java, C++, or Python.