1

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

To be clear, the sign is specified when negative numbers are involved only in C++11, in C++ a%b may yield both a positive or a negative number if one or both of the operands are negative(a%b is NOT the same of a%(-b) it is implementation dependent, unless you enable c++11 or you implement your own modulus function).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.