The single most important primitive in 2D geometry. Exact in integers, and it answers orientation, area and parallelism at once.
long long cross(const P& a, const P& b) { return a.x * b.y - a.y * b.x; }
long long cross(const P& o, const P& a, const P& b) { // relative to origin o
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
}What the sign means
This is the orientation test, and it is the basis of:
| Task | Test |
|---|---|
| Is left of the line ? | |
| Are three points collinear? | |
| Convex hull turn direction | sign of the cross product |
| Do segments and straddle each other? | opposite signs on both sides |
| Is a polygon CCW? | signed area |
| Is a polygon convex? | all cross products have the same sign |
| Point inside a convex polygon | same sign for every edge |
What the magnitude means
So the triangle area is , and — crucially — twice the area is an integer for integer input. Work with throughout and never divide.
Shoelace formula
for a simple polygon with . The signed version tells you the orientation as a bonus. See Polygon Area.
Distance from a point to a line
For comparisons, keep the numerator squared and the denominator squared separately, and cross-multiply — no square roots, no floating point:
// is p closer to line ab than q is?
__int128 lhs = (__int128)cross(b-a, p-a) * cross(b-a, p-a) * norm2(d-c);
__int128 rhs = (__int128)cross(d-c, q-c) * cross(d-c, q-c) * norm2(b-a);Overflow
With coordinates up to , differences reach and the cross product reaches — inside long long (), but only just. Any further multiplication needs __int128.
If coordinates can be , use __int128 from the start, or translate all points by the first point to shrink the range.
The sgn idiom
Most uses only need the sign, not the value:
int sgn(long long x) { return (x > 0) - (x < 0); }
int orient(P a, P b, P c) { return sgn(cross(a, b, c)); }Working with avoids overflow in comparisons and makes the code read as geometry rather than arithmetic.
3D cross product
a vector perpendicular to both, with length equal to the parallelogram area. Uses:
- plane normal from three points: ;
- triangle area in 3D: half the length of that;
- coplanarity of four points: the scalar triple product ;
- tetrahedron volume: of the triple product.
See 3D Geometry.
Why cross beats angles
Comparing angles requires atan2, which is slow, imprecise, and has a discontinuity at . The cross product answers the same question exactly, in integers, with two multiplications. Reach for cross first, angles only when you genuinely need a numeric angle.
See also: Dot Product · Orientation Test · Polygon Area