1135. Squares on the Board

Easy1.5 points estimatedMathsEnumeration

A tile designer lays unit tiles on a rectangular floor with m rows and n columns of cells. Count every square whose sides follow the grid lines and are made of whole cells, for every side length s from 1 up to min(m, n). Squares at different positions, or of different sizes, are all distinct.

For a given s there are (m-s+1)*(n-s+1) positions, so the answer is the sum of that product over all s. Return the total as a long, because it can exceed 32 bits; it is guaranteed to stay below 2^53. Loop over the side length for O(min(m, n)) time and O(1) space.

Example 1

Input:
m = 2, n = 3
Output:
8
Explanation:

A 2 x 3 board has 6 squares of side 1 and 2 squares of side 2, so the answer is 8.

Example 2

Input:
m = 3, n = 3
Output:
14
Explanation:

A 3 x 3 board has 9 squares of side 1, 4 of side 2 and 1 of side 3, so the answer is 14.

Constraints

1 ≤ m, n ≤ 105

The answer is less than 253

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(min(m, n))
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…