Leetcode 2894: Divisible and Non-divisible Sums Difference

grid47
grid47
Exploring patterns and algorithms
Jan 22, 2024 4 min read

You are given two positive integers, n and m. Calculate the difference between the sum of integers in the range [1, n] that are not divisible by m (num1) and the sum of integers in the range [1, n] that are divisible by m (num2). Return the result of num1 - num2.
Problem
Approach
Steps
Complexity
Input: The input consists of two integers, n and m.
Example: n = 12, m = 4
Constraints:
• 1 <= n, m <= 1000
Output: Return the value of num1 - num2, where num1 is the sum of integers not divisible by m, and num2 is the sum of integers divisible by m.
Example: For input n = 12, m = 4, the output is 58.
Constraints:
Goal: The goal is to calculate the sum of integers that are divisible by m and those that are not, and return the difference between the two sums.
Steps:
• Loop through all integers from 1 to n.
• Check if each number is divisible by m.
• If divisible, add it to num2; if not, add it to num1.
• Calculate the difference num1 - num2.
Goal: The solution must handle numbers up to 1000 efficiently.
Steps:
• 1 <= n, m <= 1000
Assumptions:
• Both n and m are positive integers.
Input: For input n = 12, m = 4, the output is 58.
Explanation: The sum of numbers in the range [1, 12] that are not divisible by 4 is 54, while the sum of numbers divisible by 4 is 24. The result is 54 - 24 = 58.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus