We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Divisible and Non-divisible Sums Difference

Difficulty: Easy


Problem Description

You are given positive integers n and m. Define two integers as follows:

  • num1: The sum of all integers in the range [1, n] (both inclusive) that are not divisible by m.
  • num2: The sum of all integers in the range [1, n] (both inclusive) that are divisible by m.

Return the integer num1 - num2.


Key Insights

  • The range of integers from 1 to n can be easily iterated over, but there are mathematical formulas to sum consecutive integers efficiently.
  • The sum of integers not divisible by m can be derived by subtracting the sum of integers that are divisible by m from the total sum of integers from 1 to n.
  • Efficiently identifying the integers divisible by m can reduce the complexity of the solution.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve this problem, we can utilize a simple loop to calculate both sums. We'll iterate through the integers from 1 to n and check if each integer is divisible by m. If it is, we add it to num2; otherwise, we add it to num1. Finally, we return the difference between num1 and num2.

The algorithm follows these steps:

  1. Initialize num1 and num2 to 0.
  2. Loop through each integer from 1 to n.
  3. Check if the integer is divisible by m.
  4. Update num1 or num2 accordingly.
  5. Return num1 - num2.

Code Solutions

def difference_of_sums(n, m):
    num1 = 0  # Sum of integers not divisible by m
    num2 = 0  # Sum of integers divisible by m

    for i in range(1, n + 1):
        if i % m == 0:
            num2 += i  # Add to num2 if divisible by m
        else:
            num1 += i  # Add to num1 if not divisible by m
    
    return num1 - num2  # Return the difference
← Back to All Questions