Integer Division and Remainder with Negative Numbers
Problem
Read two integers a and b (b is not zero). Print the quotient and the remainder separated by a space. The quotient is a / b with the decimal part removed (cut toward zero, as in Java). The remainder is a - quotient * b, so it has the sign of a. Example: -7 and 2 give -3 -1.
Constraints
- -10^9 <= a, b <= 10^9
- b != 0
Examples
Input
-7 2
Output
-3 -1
Solutions
Languages disagree about negative numbers. Java and JavaScript cut toward zero. Python rounds down, so Python's // and % behave differently. Knowing the rule avoids bugs.
/*
* Problem : Divide two integers and cut the decimal part (toward zero).
* Input : Two integers a and b (b is not 0).
* Output : The quotient and the remainder.
* Approach: Quotient is cut toward zero.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
// Step 1: Java divides two int values and cuts the decimal part toward zero.
int quotient = a / b;
// Step 2: The % operator gives the remainder. It has the same sign as a.
int remainder = a % b;
// Step 3: Print both values.
System.out.println(quotient + " " + remainder);
}
}
Hints (2)
- What is -7 / 2 as a decimal?
- Which direction does your language round?