021. How Many Voxels Does the Ray Pass Through?

Let a cube with side length 1 be called a voxel. Given natural numbers ll, mm, nn, stack lmnlmn voxels to form a rectangular parallelepiped with side lengths ll, mm, and nn respectively. Determine the number of voxels through which one diagonal of this rectangular parallelepiped passes internally.


The positions of lmnlmn voxels can be represented using coordinates as follows. (x,y,z)1xl,1ym,1zn\begin{aligned} (x, y, z) \qquad 1 \leq x \leq l, \quad 1 \leq y \leq m, \quad 1 \leq z \leq n \end{aligned}

This is represented by the highest number among the coordinates of the eight vertices of a single voxel. Now, when the diagonal is defined as the ray moving from the origin (0,0,0)(0, 0, 0) to the point (l,m,n)(l, m, n), the total coordinate change is l+m+nl + m + n.

  • The ray passes through a voxel’s face (excluding the boundary lines)
    • When moving to the next voxel, only one of the (x,y,z)(x, y, z) coordinates increases by 1.
  • The ray passes through a voxel’s edge (excluding vertices)
    • When moving to the next voxel, only two of the (x,y,z)(x, y, z) coordinates increase by 1.
  • The ray passes through a voxel’s vertex
    • When moving to the next voxel, all of the (x,y,z)(x, y, z) coordinates increase by 1.

That is, l+m+nl + m + n can be viewed as a value calculated assuming the ray only passed through the faces of voxels. Therefore, this value must be adjusted to obtain the actual number of voxels traversed. When gcd()gcd() is defined as the function representing the greatest common divisor, the following can be determined.

  • The ray passes through gcd(m,n)gcd(m, n) edges parallel to the xx-axis.
  • The ray passes through gcd(l,n)gcd(l, n) edges parallel to the yy-axis.
  • The ray passes through gcd(l,m)gcd(l, m) edges parallel to the zz-axis.

l+m+nl + m + n assumes the ray traverses only faces, but when it actually crosses edges, two coordinate changes occur in a single movement. Therefore, the number of edges traversed by the ray must be subtracted. Additionally, cases where the ray passes through a vertex, causing all three coordinates to change, must be included. However, since this subtraction causes such cases to be deducted redundantly, gcd(l,m,n)gcd(l, m, n) must be added back. Therefore, the number of voxels traversed by this ray is as follows. l+m+ngcd(l,m)gcd(m,n)gcd(l,n)+gcd(l,m,n)\begin{aligned} l + m + n - gcd(l, m) - gcd(m, n) - gcd(l, n) + gcd(l, m, n) \end{aligned}


© 2025. All rights reserved.