Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created May 27, 2025 22:07
Show Gist options
  • Save Ifihan/107e1c191d4a85ab333a65a5ecb19b74 to your computer and use it in GitHub Desktop.
Save Ifihan/107e1c191d4a85ab333a65a5ecb19b74 to your computer and use it in GitHub Desktop.
Divisible and Non-divisible Sums Difference

Question

Approach

I calculated the total sum from 1 to n using the formula n * (n + 1) // 2. Then, I found how many numbers are divisible by m (n // m) and used the arithmetic series formula to get their sum. Finally, I subtracted the divisible sum from the total to get the difference between non-divisible and divisible sums.

Implementation

class Solution:
    def differenceOfSums(self, n: int, m: int) -> int:
        total_sum = n * (n + 1) // 2

        k = n // m

        divisible_sum = m * k * (k + 1) // 2

        return total_sum - 2 * divisible_sum

Complexities

  • Time: O(1)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment