English

Counting All Lattice Rectangles in the Square Grid in Near-Linear Time

Computational Geometry 2026-05-04 v2

Abstract

We study the exact counting problem for all lattice rectangles contained in the square [0,n)×[0,n)[0,n)\times[0,n), including non-axis-parallel ones. Starting from the standard parametrization by a primitive direction (u,v)(u,v) and two side lengths, we derive several exact algorithms: the classical O(n2)O(n^2) sweep, decompositions of complexity O(n3/2logn)O(n^{3/2}\log n) and O(n4/3logn)O(n^{4/3}\log n), a ten-moment weighted-floor-sum reduction of complexity O(nlog3n)O(n\log^3 n), and a divisor-layer algorithm with the complexity O(nlog2n)O(n\log^2 n). We also give an all-values algorithm that computes F(1),,F(N)F(1),\ldots,F(N) in O(N3/2)O(N^{3/2}) arithmetic operations. The main idea behind the near-linear one-value algorithms is to reduce the geometric summation to constant-size families of weighted floor sums closed under Euclidean-style affine and reciprocal transformations. Besides the exact algorithmic results, we derive a two-term asymptotic expansion, F(n)=4log21π2n4logn+Bn4+o(n4)F(n)=\frac{4\log 2-1}{\pi^2}n^4\log n+B\,n^4+o(n^4) with the explicit formula for BB, which provides an independent consistency check for the large-nn numerical data produced by the algorithms.

Keywords

Cite

@article{arxiv.2604.22456,
  title  = {Counting All Lattice Rectangles in the Square Grid in Near-Linear Time},
  author = {Dmitry Babichev and Sergey Babichev},
  journal= {arXiv preprint arXiv:2604.22456},
  year   = {2026}
}

Comments

Full version of an extended abstract submitted to MFCS 2026. Updated version with new near-linear and all-values algorithms, plus expanded experiments