▶ YouTube Summaries

← All summaries

Fastest way to compute the day of the week

2026-09-17 Thu ⏱ 11 min theprimeagen

A rare pure-technical Primeagen video: a walkthrough of Ben Joffe's article on computing the day of the week from a day count since the Unix epoch, deriving the naive formula, then Henan's branch-based version, and finally Neri's algorithm, which collapses the whole thing into a signed-to-unsigned reinterpretation that happens to line up with the epoch offset.

The naive formula and why it breaks

The question is: what weekday is day N since the epoch? Number the days Sunday=0 through Saturday=6. The obvious answer is daycount % 7, but for N=57 that gives 1 instead of the correct Friday=5. The epoch itself fell on a Thursday, so the offset 4 must be added: (daycount + 4) % 7. That works for positive inputs, but pre-epoch dates give negative results, because C-style modulo of a negative number ranges from -6 to 0.

The generalized fix is ((daycount % 7) + 7 + 4) % 7. Adding 7 before the second modulo shifts everything into positive territory without changing the result. Correct, but it costs two modulo operations, which is too slow for a date library or a database.

Henan's algorithm (2014)

Replaces the second modulo with a branch. For daycount > -4= the simplified formula already works, so only the more-negative range needs a different expression: shift the -6..0 range up by 6. What makes it elegant is pure coincidence — the +6 shift happens to land exactly on the right weekday, because daycount + 5 maps -5 to zero and 6 is Thursday's neighbour in the cycle.

Neri's algorithm and the bit trick

The payoff. Reinterpreting a signed integer as unsigned is free — it is the same bits. For a signed 8-bit value, -5 reinterpreted as unsigned is 251, i.e. 256 -

  1. And 256 mod 7 is 4 — which is exactly Thursday, the epoch offset. The same

alignment holds for u32. So reinterpreting a negative signed day count as unsigned automatically applies the epoch correction; the positive branch just needs the explicit +4 added back.

The video stops there and points at the article for the rest, which draws on Hacker's Delight for bit-manipulation tricks. The claim in the article is that on real machines the weekday can be computed in a single machine operation.

Aside on two's complement

For viewers unfamiliar with binary, the video recaps two's complement: flip every bit of the positive value, then add one. The top bit set means negative. This is the mechanism that makes the reinterpretation trick work.