carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2894: Divisible and Non-divisible Sums Difference #438

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

You are given positive integers n and m.

Define two integers, num1 and num2, as follows:

num1: The sum of all integers in the range [1, n] that are not divisible by m. num2: The sum of all integers in the range [1, n] that are divisible by m. Return the integer num1 - num2.

Example 1:

Input: n = 10, m = 3 Output: 19 Explanation: In the given example:

Example 2:

Input: n = 5, m = 6 Output: 15 Explanation: In the given example:

Example 3:

Input: n = 5, m = 1 Output: -15 Explanation: In the given example:

Constraints:

1 <= n, m <= 1000

carloscn commented 11 months ago

Analysis

static int32_t difference_of_sums(int32_t n, int32_t m)
{
    int32_t ret = 0;

    if ((n == 0) && (m == 0)) {
        goto finish;
    }

    for (int32_t i = 0; i <= n; i ++) {
        if ((i % m) == 0) {
            ret -= i;
        } else {
            ret += i;
        }
    }

finish:
    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1173420 https://github.com/carloscn/structstudy/commit/d099db47162ae8ce03ccb83a2041d0d157425a64