basics · intermediate · ~20 min
Apply a closed-form formula with several branching cases.
Implement int day_of_week(int y, int m, int d) returning the day of the week (0=Saturday, 1=Sunday, … 6=Friday) for the Gregorian date (y, m, d). Use Zeller's congruence.
Zeller (Gregorian): treat January and February as months 13 and 14 of the previous year; then
h = (d + (13*(m+1))/5 + K + K/4 + J/4 - 2*J) mod 7 where K = y mod 100, J = y / 100.
Calendar arithmetic shows up in log timestamps, scheduling, and security policies. Zeller's congruence is a clean way to teach modular branching.
Gregorian date (y, m, d).
0..6.
No system calls; pure arithmetic.
int day_of_week(int y, int m, int d) { /* TODO */ return 0; }
Forgetting the Jan/Feb shift. Mishandling negative modulo (C99: (-1) % 7 == -1).
Jan/Feb (shift), year 2000 (boundary), pre-Gregorian years (formula doesn't apply).
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.