Problem. people stand in a circle. Starting from position 1, every -th person is eliminated, and the circle closes up. Who survives?
The recurrence β
Let be the survivorβs 0-indexed position.
After the first elimination, people remain in a circle whose numbering is shifted by .
int josephus(int n, int k) { // 0-indexed survivor
int r = 0;
for (int i = 2; i <= n; i++) r = (r + k) % i;
return r; // add 1 for 1-indexed
}time, space.
The case β a closed form
or in one line: write in binary and rotate its leading 1 to the end.
int josephus2(int n) { // 1-indexed survivor
int highBit = 1 << (31 - __builtin_clz(n));
return 2 * (n - highBit) + 1;
}For (Josephusβs own legendary case with , but with ): .
The bit-rotation form is a good example of a combinatorial recurrence with a clean binary description β the same flavour as Hanoiβs ctz rule.
Large , small β
When is up to but is small, the recurrence can be batched: while , many consecutive steps just add without wrapping, so they can be skipped in one jump.
long long josephusBig(long long n, long long k) {
if (k == 1) return n - 1;
long long r = 0;
for (long long i = 2; i <= n; ) {
if (r + k < i) { // how many steps until the next wrap
long long steps = (i - r - 1) / k;
steps = min(steps, n - i + 1);
r += steps * k;
i += steps;
} else {
r = (r + k) % i;
i++;
}
}
return r;
}β the number of wraps is because each wrap roughly multiplies by .
Variants
| Variant | Method |
|---|---|
| Survivorβs position | the recurrence above |
| Order of elimination | simulate with an order-statistics tree or a BIT, |
| survivors | run the recurrence from upward |
| Elimination direction alternates | modify the recurrence |
| Variable step | the same recurrence with |
| Josephus on a line (no wraparound) | a different, simpler problem |
| , huge | the bit rotation, |
Order of elimination in
Keep the survivors in a BIT over positions; to find the -th remaining person, do a BIT descent:
int kth(int k) { // k-th remaining, 1-indexed
int pos = 0;
for (int pw = 1 << LOG; pw; pw >>= 1)
if (pos + pw <= n && bit[pos + pw] < k) { pos += pw; k -= bit[pos]; }
return pos + 1;
}
// then repeatedly: cur = ((cur + k - 1 - 1) % remaining) + 1; erase kth(cur);total, and it outputs the full elimination sequence β which most contest versions of this problem actually want.
The history
Flavius Josephus, in the Jewish-Roman war, was trapped with 40 companions who preferred suicide to capture. They arranged themselves in a circle to be killed every third man. Josephus β a mathematician β placed himself and a friend at the surviving positions.
Why it is worth knowing
It is the standard example of a problem where the recurrence is easy and the closed form is surprising. The bit rotation, and the batching trick for large , are both techniques that transfer: whenever a recurrence adds a constant modulo a growing bound, batching the non-wrapping steps turns into .
See also: Tower of Hanoi Β· Fenwick Tree Β· Classical Problems