Perform the Five Basic Arithmetic Operations

Solve this Problem
Easy5 min
Topics
Companies
Given two integers a and b (with b at least 1), return five results in order: a + b, a - b, a × b, the whole-number quotient of a ÷ b, and the remainder. These five operators are the building blocks of almost every program. Addition, subtraction and multiplication behave the way you expect. Division between whole numbers is the one to watch: integer divisionInteger DivisionDividing two whole numbers and keeping only the whole part of the answer, e.g. 17 / 5 = 3. keeps only how many whole times b fits, and the modulo operatorModulo (%)Gives the remainder left after integer division, e.g. 17 % 5 = 2. reports what is left over. The second solution shows that the two are tied together: the remainder can be rebuilt from the quotient.

Test Case 1:

Input:a = 17, b = 5
Output:[22, 12, 85, 3, 2]
Explanation:Sum, difference, product, then 5 fits into 17 three whole times with 2 left over.

Test Case 2:

Input:a = 4, b = 9
Output:[13, -5, 36, 0, 4]
Explanation:b is bigger: the difference is negative, 9 fits zero times, and all of 4 is the remainder.

Constraints

  • ◆0 ≤ a ≤ 10000
  • ◆1 ≤ b ≤ 10000

Try the Dry Run

Approach & Solutions

One Variable per OperationOptimal

Apply each operator once and keep its answer in a clearly named variable: + for the sum, - for the difference, * for the product, / for the integer quotient and % for the remainder. Then return the five values in that order. Python uses // for whole-number division and JavaScript wraps a / b in Math.trunc to drop the fraction.

TimeO(1)
SpaceO(1)
class Solution { public int[] arithmeticResults(int a, int b) { int total = a + b; int difference = a - b; int product = a * b; int quotient = a / b; int remainder = a % b; return new int[] {total, difference, product, quotient, remainder}; } }
Derive the Remainder from the QuotientGood

Division and remainder are linked: a = quotient × b + remainder. So once the quotient is known, the remainder is just a - quotient × b — no % operator needed. The sum, difference and product are written straight into the result. This makes the relationship between / and % visible.

TimeO(1)
SpaceO(1)
class Solution { public int[] arithmeticResults(int a, int b) { int quotient = a / b; int remainder = a - quotient * b; return new int[] {a + b, a - b, a * b, quotient, remainder}; } }

Related Problems