Problem. people stand in a circle; counting starts at person , and every -th person is removed. Who survives? (Josephus, 1st century; the CP classic.)

VariantMethodCost
any ,
huge , small remove a whole lap ( people) at once
(1-indexed): rotate ‘s binary representation left by one
order of eliminationorder-statistics tree / BIT: find the next -th alive
-th eliminated personthe same recurrence on the last people
long long josephus(long long n, long long k) {     // 0-indexed survivor; O(k log n) for large n, O(n) for small n
    if (n == 1) return 0;
    if (k == 1) return n - 1;
    if (k > n) return (josephus(n - 1, k) + k) % n;
    long long r = josephus(n - n / k, k) - n % k;  // one full pass removes n / k people
    if (r < 0) r += n;
    else r += r / (k - 1);
    return r;
}
long long josephus2(long long n) {                 // k = 2, 1-indexed: rotate the binary representation left
    long long h = 1LL << (63 - __builtin_clzll(n));
    return 2 * (n - h) + 1;
}