You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Math/#2894 - DIvisible and non-divisible sums difference - Easy/Explaination.md
+65-27Lines changed: 65 additions & 27 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -8,36 +8,75 @@
8
8
9
9
## 📝 Introduction
10
10
11
-
*A brief introduction to the problem. Mention the key aspects, constraints, and expected output.*
11
+
You're given two integers, n and m. Your task is to calculate the difference between:
12
+
13
+
num1: the sum of all numbers from 1 to n not divisible by m.
14
+
15
+
num2: the sum of all numbers from 1 to n divisible by m.
16
+
17
+
Return the value of num1 - num2.
12
18
13
19
---
14
20
15
21
## 💡 Approach & Key Insights
16
22
17
-
*Describe the main idea behind solving the problem. What observations lead to a solution? Mention brute force or naive approaches first, then discuss optimal solutions.*
23
+
The total sum of numbers from 1 to n is known via the formula: n(n + 1) / 2.
24
+
25
+
The sum of numbers divisible by m is also a simple arithmetic series.
26
+
27
+
Subtracting 2 * (sum of numbers divisible by m) from the total sum gives us num1 - num2.
28
+
29
+
18
30
19
31
---
20
32
21
33
## 🛠️ Breakdown of Approaches
22
34
23
35
### 1️⃣ Brute Force / Naive Approach
24
36
25
-
-**Explanation:***Describe the brute force solution and why it works.*
26
-
-**Time Complexity:***O(?) - Explanation*
27
-
-**Space Complexity:***O(?) - Explanation*
37
+
-**Explanation:** Loop through all numbers from 1 to n. For each number:
38
+
39
+
If it is divisible by m, add to num2.
40
+
41
+
Else, add to num1.
42
+
Finally return num1 - num2.
43
+
-**Time Complexity:***O(?) - because we loop from 1 to n.*
44
+
-**Space Complexity:***O(?) - constant space for sums.*
*Are there any ways to further improve the solution? Can we reduce memory usage or optimize certain operations?*
105
+
The optimized solution already achieves constant time and space using mathematical formulas. No further optimization is necessary unless extending to very large ranges, in which case care for integer overflow may be required.
67
106
68
107
---
69
108
70
109
## 📌 Example Walkthroughs & Dry Runs
71
110
72
-
*Use visuals, ASCII diagrams, or step-by-step breakdowns for clarity.*
0 commit comments