Counting Rectangles
By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles:
Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution.
Implementations
#include <iostream>#include <cmath>#include <climits>
int counting_rectangles() { long long target = 2000000; long long min_diff = LLONG_MAX; int best_area = 0; for (int m = 1; m <= 2000; ++m) { for (int n = 1; n <= 2000; ++n) { long long rect = (long long)m * (m + 1) / 2 * n * (n + 1) / 2; long long diff = std::abs(rect - target); if (diff < min_diff) { min_diff = diff; best_area = m * n; } } } return best_area;}Solution Notes
Mathematical Background
A grid of m by n points contains rectangles formed by choosing 2 horizontal lines from m+1 possible and 2 vertical lines from n+1 possible. The number of rectangles is C(m+1,2) * C(n+1,2) = [m(m+1)/2] * [n(n+1)/2].
Algorithm Analysis
Brute force search over possible m,n dimensions (up to 2000) to find the combination where rectangle count is closest to 2,000,000. Uses the triangle number formula for efficiency.
Time complexity: O(M*N) where M=N=2000, very fast due to small constants. Space complexity: O(1), only tracking minimum difference and best area.
Performance
Extremely fast across all implementations (<100ms), as the nested loops are small and computation is simple.
Key Insights
The optimal grid dimensions are around 36x77 or similar, giving area 2772 with rectangle count very close to 2 million.
Educational Value
Demonstrates how combinatorial formulas can be used to count geometric objects in grids, and how brute force can efficiently solve optimization problems with bounded search spaces.
Problem #85 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.