FastPrepSum of Remainders Across Integer Ranges
Problem · Math

Sum of Remainders Across Integer Ranges

Learn this problem
MediumIBM logoIBMFULLTIMEOA
See IBM hiring insights

Problem statement

Given two nonnegative integers i and j, consider every pair (a, b) with 0 <= a <= i and 1 <= b <= j.

Return the sum of a % b over all these pairs, where % is the remainder after integer division.

The original ranges include zero. For this exercise, pairs whose divisor is zero are excluded because their remainder is undefined. If j = 0, there are no valid pairs and the result is 0.

Function

sumRemainders(i: int, j: int) → long

Examples

Example 1

i = 3j = 2return = 2

For divisor 1, every remainder is zero. For divisor 2, dividends 0, 1, 2, 3 produce 0, 1, 0, 1. The total is 2.

Example 2

i = 2j = 3return = 4

The sums for divisors 1, 2, and 3 are 0, 1, and 3. Their total is 4.

Constraints

  • 0 <= i, j <= 1000000
  • Return the exact sum as a signed 64-bit integer.

More IBM problems

drafts saved locally
public long sumRemainders(int i, int j) {
    // Write your code here
}
i3
j2
expected2
checking account