Josephus Problem when k is 2
Last Updated :
23 Jul, 2025
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.
We have discussed a generalized solution in below set 1.
Josephus problem | Set 1 (A O(n) Solution)
In this post, a special case is discussed when k = 2
Examples :
Input : n = 5
Output : The person at position 3 survives
Explanation : Firstly, the person at position 2 is killed,
then at 4, then at 1 is killed. Finally, the person at
position 5 is killed. So the person at position 3 survives.
Input : n = 14
Output : The person at position 13 survives
Below are some interesting facts.
- In first round all even positioned persons are killed.
- For second round two cases arise
- If n is even : For example n = 8. In first round, first 2 is killed, then 4, then 6, then 8. In second round, we have 1, 3, 5 and 7 in positions 1st, 2nd, 3rd and 4th respectively.
- If n is odd : For example n = 7. In first round, first 2 is killed, then 4, then 6. In second round, we have 3, 5, 7 in positions 1st, 2nd and 3rd respectively.
If n is even and a person is in position x in current round, then the person was in position 2x - 1 in previous round.
If n is odd and a person is in position x in current round, then the person was in position 2x + 1 in previous round.
From above facts, we can recursively define the formula for finding position of survivor.
Let f(n) be position of survivor for input n,
the value of f(n) can be recursively written
as below.
If n is even
f(n) = 2f(n/2) - 1
Else
f(n) = 2f((n-1)/2) + 1
Solution of above recurrence is
f(n) = 2(n - 2floor(Log2n) + 1
= 2n - 21 + floor(Log2n) + 1
Below is the implementation to find value of above formula.
C++
// C/C++ program to find solution of Josephus
// problem when size of step is 2.
#include <stdio.h>
// Returns position of survivor among a circle
// of n persons and every second person being
// killed
int josephus(int n)
{
// Find value of 2 ^ (1 + floor(Log n))
// which is a power of 2 whose value
// is just above n.
int p = 1;
while (p <= n)
p *= 2;
// Return 2n - 2^(1+floor(Logn)) + 1
return (2 * n) - p + 1;
}
// Driver Program to test above function
int main()
{
int n = 16;
printf("The chosen place is %d", josephus(n));
return 0;
}
Java
// Java program to find solution of Josephus
// problem when size of step is 2.
import java.io.*;
class GFG {
// Returns position of survivor among
// a circle of n persons and every
// second person being killed
static int josephus(int n)
{
// Find value of 2 ^ (1 + floor(Log n))
// which is a power of 2 whose value
// is just above n.
int p = 1;
while (p <= n)
p *= 2;
// Return 2n - 2^(1+floor(Logn)) + 1
return (2 * n) - p + 1;
}
// Driver Program to test above function
public static void main(String[] args)
{
int n = 16;
System.out.println("The chosen place is "
+ josephus(n));
}
}
// This Code is Contributed by Anuj_67
Python3
# Python3 program to find solution of
# Josephus problem when size of step is 2.
# Returns position of survivor among a
# circle of n persons and every second
# person being killed
def josephus(n):
# Find value of 2 ^ (1 + floor(Log n))
# which is a power of 2 whose value
# is just above n.
p = 1
while p <= n:
p *= 2
# Return 2n - 2^(1 + floor(Logn)) + 1
return (2 * n) - p + 1
# Driver Code
n = 16
print ("The chosen place is", josephus(n))
# This code is contributed by Shreyanshi Arun.
C#
// C# program to find solution of Josephus
// problem when size of step is 2.
using System;
class GFG {
// Returns position of survivor among
// a circle of n persons and every
// second person being killed
static int josephus(int n)
{
// Find value of 2 ^ (1 + floor(Log n))
// which is a power of 2 whose value
// is just above n.
int p = 1;
while (p <= n)
p *= 2;
// Return 2n - 2^(1+floor(Logn)) + 1
return (2 * n) - p + 1;
}
// Driver Program to test above function
static void Main()
{
int n = 16;
Console.Write("The chosen place is "
+ josephus(n));
}
}
// This Code is Contributed by Anuj_67
PHP
<?php
// PHP program to find solution
// of Josephus problem when
// size of step is 2.
// Returns position of survivor
// among a circle of n persons
// and every second person being
// killed
function josephus($n)
{
// Find value of 2 ^ (1 + floor(Log n))
// which is a power of 2 whose value
// is just above n.
$p = 1;
while ($p <= $n)
$p *= 2;
// Return 2n - 2^(1+floor(Logn)) + 1
return (2 * $n) - $p + 1;
}
// Driver Code
$n = 16;
echo "The chosen place is ", josephus($n);
// This code is contributed by ajit.
?>
JavaScript
<script>
// Javascript program to find solution of Josephus
// problem when size of step is 2.
// Returns position of survivor among
// a circle of n persons and every
// second person being killed
function josephus(n)
{
// Find value of 2 ^ (1 + floor(Log n))
// which is a power of 2 whose value
// is just above n.
let p = 1;
while (p <= n)
p *= 2;
// Return 2n - 2^(1+floor(Logn)) + 1
return (2 * n) - p + 1;
}
// Driver code
let n = 16;
document.write("The chosen place is " +
josephus(n));
// This code is contributed by susmitakundugoaldanga
</script>
Output: The chosen place is 1
Time complexity of above solution is O(Log n).
An another interesting solution to the problem while k=2 can be given based on an observation, that we just have to left rotate the binary representation of N to get the required answer. A working code for
the same is provided below considering number to be 64-bit number.
Below is the implementation of the above approach:
C++
// C++ program to find solution of Josephus
// problem when size of step is 2.
#include <bits/stdc++.h>
using namespace std;
// Returns position of survivor among a circle
// of n persons and every second person being
// killed
int josephus(int n)
{
// An interesting observation is that
// for every number of power of two
// answer is 1 always.
if (!(n & (n - 1)) && n) {
return 1;
}
// The trick is just to right rotate the
// binary representation of n once.
// Find whether the number shed off
// during left shift is set or not
bitset<64> Arr(n);
// shifting the bitset Arr
// f will become true once leftmost
// set bit is found
bool f = false;
for (int i = 63; i >= 0; --i) {
if (Arr[i] == 1 && !f) {
f = true;
Arr[i] = Arr[i - 1];
}
if (f) {
// shifting bits
Arr[i] = Arr[i - 1];
}
}
Arr[0] = 1;
int res;
// changing bitset to int
res = (int)(Arr.to_ulong());
return res;
}
// Driver Program to test above function
int main()
{
int n = 16;
printf("The chosen place is %d", josephus(n));
return 0;
}
Java
public class Main {
public static int josephus(int n)
{
// An interesting observation is that
// for every number of power of two
// answer is 1 always.
if (~((n & (n - 1))) != 0 && n != 0) {
return 1;
}
// The trick is just to right rotate the
// binary representation of n once.
// Find whether the number shed off
// during left shift is set or not
int[] arr = new int[64];
char[] bin = Integer.toBinaryString(n).toCharArray();
int i = 64 - bin.length;
for (int j = 0; j < bin.length; j++) {
arr[i++] = bin[j] - '0';
}
// shifting the bitset arr
// f will become true once leftmost
// set bit is found
boolean f = false;
for (i = 63; i >= 0; i--) {
if (arr[i] == 1 && !f) {
f = true;
arr[i] = arr[i - 1];
}
if (f) {
// shifting bits
arr[i] = arr[i - 1];
}
}
arr[0] = 1;
// changing bitset to int
int res = 0;
for (i = 0; i < 64; i++) {
res += arr[i] * (1L << (63 - i));
}
return res;
}
public static void main(String[] args) {
int n = 16;
System.out.println("The chosen place is " + josephus(n));
}
}
Python3
# Python 3 program to find solution of Josephus
# problem when size of step is 2.
# Returns position of survivor among a circle
# of n persons and every second person being
# killed
def josephus(n):
# An interesting observation is that
# for every number of power of two
# answer is 1 always.
if (~(n & (n - 1)) and n) :
return 1
# The trick is just to right rotate the
# binary representation of n once.
# Find whether the number shed off
# during left shift is set or not
Arr=list(map(lambda x:int(x),list(bin(n)[2:])))
Arr=[0]*(64-len(Arr))+Arr
# shifting the bitset Arr
# f will become true once leftmost
# set bit is found
f = False
for i in range(63,-1,-1) :
if (Arr[i] == 1 and not f) :
f = True
Arr[i] = Arr[i - 1]
if (f) :
# shifting bits
Arr[i] = Arr[i - 1]
Arr[0] = 1
# changing bitset to int
res = int(''.join(Arr),2)
return res
# Driver Program to test above function
if __name__ == '__main__':
n = 16
print("The chosen place is", josephus(n))
C#
using System;
public class Mainn
{
public static long josephus(long n)
{
// An interesting observation is that
// for every number of power of two
// answer is 1 always.
if (~((n & (n - 1))) != 0 && n != 0)
{
return 1;
}
// The trick is just to right rotate the
// binary representation of n once.
// Find whether the number shed off
// during left shift is set or not
int[] arr = new int[64];
char[] bin = Convert.ToString(n, 2).ToCharArray();
int i = 64 - bin.Length;
for (int j = 0; j < bin.Length; j++)
{
arr[i++] = bin[j] - '0';
}
// shifting the bitset arr
// f will become true once leftmost
// set bit is found
bool f = false;
for (i = 63; i >= 0; i--)
{
if (arr[i] == 1 && !f)
{
f = true;
arr[i] = arr[i - 1];
}
if (f)
{
// shifting bits
arr[i] = arr[i - 1];
}
}
arr[0] = 1;
// changing bitset to long
long res = 0;
for (i = 0; i < 64; i++)
{
res += arr[i] * (1L << (63 - i));
}
return res;
}
public static void Main(string[] args)
{
long n = 16;
Console.WriteLine("The chosen place is " + josephus(n));
}
}
JavaScript
function josephus(n) {
// An interesting observation is that
// for every number of power of two
// answer is 1 always.
if (~(n & (n - 1)) && n) {
return 1;
}
// The trick is just to right rotate the
// binary representation of n once.
// Find whether the number shed off
// during left shift is set or not
let Arr = n.toString(2).split('').map(x => parseInt(x));
Arr = Array(64 - Arr.length).fill(0).concat(Arr);
// shifting the bitset Arr
// f will become true once leftmost
// set bit is found
let f = false;
for (let i = 63; i >= 0; i--) {
if (Arr[i] == 1 && !f) {
f = true;
Arr[i] = Arr[i - 1];
}
if (f) {
// shifting bits
Arr[i] = Arr[i - 1];
}
}
Arr[0] = 1;
// changing bitset to int
let res = parseInt(Arr.join(''), 2);
return res;
}
// Driver Program to test above function
let n = 16;
console.log("The chosen place is", josephus(n));
Output: The chosen place is 1
Time Complexity : O(log(n))
Auxiliary Space: O(log(n))
This idea is contributed by Anukul Chand.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem