puwi
puwi

Reputation: 35

Division and Mod with negative numbers

I'm trying to solve a contest problem that was supposed to be simple.

What is the result of the quotient q and remainder r for 2 numbers a and b (-1.000 ≤ a, b < 1.000)?

The input consist of 2 numbers a and b.

Example of 3 different inputs:
7 3
7 -3
-7 3

The output is the quotient q followed by the remainder r of the division of a by b.

Example of output:
2 1
-2 1
-3 2

My code :

#include<stdio.h>
int main(){
    int a,b;
    scanf("%d %d",&a,&b);

    int r = 0;
    if(a > 0)
        r = a%b;
    if(a < 0)
        r = (a%b + b)%b;


    printf("%d %d\n",(a-r)/b,r);
}

My solution is wrong in 10% of the test cases and i don't know what is wrong.

Upvotes: 1

Views: 2976

Answers (1)

Douglas Zare
Douglas Zare

Reputation: 3316

The problem with your code is that it doesn't follow the specifications when b is negative.

a%b is the same as a%(-b) in some implementations of C++. (Thanks to DarioOO for clarifying this. See DarioOO's comment.) Suppose that is the case here. Your code

if(a < 0)
    r = (a%b + b)%b;

assumes that b is positive. If b=-3 and a=-7, then a%b is -1, and your code assigns r=(-4)%(-3) which is -1. You are supposed to produce a nonnegative remainder, 2. If b<0, you want

if(a < 0)
    r = (a%b - b)%b;

instead.

Upvotes: 1

Related Questions