Home > other >  Find the remainder after dividing the sum of two integers by the third
Find the remainder after dividing the sum of two integers by the third

Time:07-25

I'm trying to find a solution to a task. My code passed only 3 autotests. I checked that the solution satisfies the max/min cases. Probably there are situations when my code is not valid.

Description of the task: Find the remainder after dividing the sum of two integers by the third.

Input: The first line of input contains two integers A and B (-10^18 ≤ A, B ≤ 10^18). The second line contains an integer C (2 ≤ C 10^9).

Output: Print the remainder of dividing A B by C.

My code:

#include <iostream>
// int64_t
#include <cstdint>
#include <stdint.h>

// #include <math.h>

// 3 tests passed
int main() {
    int64_t a, b, c;
    std::cin >> a >> b >> c;

    // a = pow(-10, 18);
    // b = pow(-10, 18);
    // // c = pow(10, 9);
    // c = 3;

    // c = pow(10, 18) - 20;
    // c = 1000000000000000000   1;
    // c = 1000000000000000000   2;


    // std::cout << a << std::endl;
    // std::cout << b << std::endl;
    // std::cout << c << std::endl;

    std::cout << (a   b) % c << std::endl;

    return 0;
}

CodePudding user response:

Modulo operation in C uses truncated division, i.e., the result of x % y is negative if x is negative.

To obtain a non-negative result congruent to (a b) % c, you can use ((a b) % c c) % c.

CodePudding user response:

Please note that in C reminder for negative values:

  • was implementation defined until C 11
  • integer division is rounded towards zero since C 11 which makes reminder negative sometimes.

Now most probably in your task modulo result should be always in range <0, C) (or written differently <0, C - 1>). So to handle cases where A B is negative, you have to take this into account that reminder may be negative.

So your code can look like this:

nt main() {
    int64_t a, b, c;
    std::cin >> a >> b >> c;
    std::cout << (a   b) % c   ((a   b) % c < 0) * c << '\n';

    return 0;
}

Which basically adds c to result if result is negative and makes result inside required range. (assuming c is positive).

  •  Tags:  
  • c
  • Related