## Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

## Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

- Notifications

- DSA for Beginners
- DSA Tutorial
- Data Structures
- Linked List
- Dynamic Programming
- Binary Tree
- Binary Search Tree
- Divide & Conquer
- Mathematical
- Backtracking
- Branch and Bound
- Pattern Searching

- Explore Our Geeks Community
- Highest power of 2 less than or equal to given number
- Sum of bit differences for numbers from 0 to N | Set 2
- Minimum comparisons required to find the only heavier ball from N balls
- Print all combinations | Set-2
- Program for Chocolate and Wrapper Puzzle
- Count unset bits in a range
- Count number of 0s in base K representation of a number
- Break the number N in odd powers of 2
- Recursive Program to print multiplication table of a number
- Count total unset bits in all the numbers from 1 to N
- Count of operations to make numbers equal by adding power of 2
- Number of continuous reductions of A from B or B from A to make them (1, 1)
- Find ways an Integer can be expressed as sum of n-th power of unique natural numbers
- Maximum possible time that can be formed from four digits | (Recursive Approach)
- Compute the maximum power with a given condition
- Knuth's Up-Arrow Notation For Exponentiation
- Count of divisors having more set bits than quotient on dividing N
- Find smallest number n such that n XOR n+1 equals to given k.
- Find m-th summation of first n natural numbers.

## Josephus Problem

- Discuss(80+)

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 the kth person is killed in a circle. The task is to choose the person in the initial circle that survives.

Input: N = 5 and k = 2 Output: 3 Explanation: Firstly, the person at position 2 is killed, then the person at position 4 is killed, then the person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. Input: N = 7 and k = 3 Output: 4 Explanations: The persons at positions 3, 6, 2, 7, 5, and 1 are killed in order, and the person at position 4 survives.

## Josephus problem using List :

The simple approach is to create a list and add all values from 1 to N to it. Create a recursive function that takes a list, start (position at which counting will start), and k ( number of people to be skipped) as an argument. If the size of the list is one i.e. only one person left then return this position. Otherwise, start counting the k person in a clockwise direction from starting position and remove the person at the kth position. Now the person at the kth position is removed and now counting will start from this position. This process continues till only one person is left.

## Pseudocode :

Josephus( list , start , k){ if list.size = 1 return list[0] start = (start + k) % list.size list.remove( start ) return Josephus( list, start, k) }

Follow the below steps to Implement the idea:

- Create a vector person and push all the values from 1 to N in person.
- Erase the element on the position index.
- Call for (index + k)% size of person.
- If size of person = 1, return person[i].

Below is the Implementation of the above approach:

Time Complexity: O(N 2 ) Auxiliary Space: O(N), For recursion stack

## Approach to solve Josephus problem iteratively:

Illustration:

N = 5, k = 2 Add all values from 1 to N in the list. We will call the recursive function with start = 0 and k = 1 (0-indexing) Now the element at 1-index (person number 2) will be killed. And it is removed from the list. The new counting will begin from 1-index, the person at 1-index killed so now person at 2-index (person number 3) comes to 1-index and counting starts from here now. Now we have 4 people, counting starting from 1-index (person number 3) and the person at kth (2-index ) position will be killed. The person at 2-index (person number 4) was killed so now we have 3 people left and the person (person number 5) at 3-index shifted to 2-index. And counting starts from here. The person at the 0-index was killed and we have now two-person left in the circle. And the person at 1-index shifted to 0-index i.e. person number 3. Final counting done and the person at 1-index killed and the only person who is left is at position 3.

- Initialize variables num , cnt , and cut with 1, 0, and 0 respectively and an array arr[] of size N with the initial value set as 1.
- Increment cut by one and take modulo by N
- If arr[cut] = 1 increment num by one.
- Set num = 1, arr[cut] = 0 and increment cnt and cut by one and cut = cut % n ;
- Run a while loop till arr[cut] = 0 and increment cut by one.
- Return cnt + 1 as the required answer.

Time Complexity: O(N 2 ) Auxiliary Space: O(N)

## Josephus Problem in Linear Time and Constant Space:

Follow the below steps to Solve the Problem (Approach):

- Initialize variables i and ans with 1 and 0 respectively.
- Update ans with (ans + k) % i.
- Increment i by 1.
- Return ans + 1 as the required answer.

Below is the Implementation of the above Steps:

Time Complexity: O(N) Auxiliary Space: O(1)

## Josephus Problem using Recursion:

Below is the idea to solve the problem:

The problem has the following recursive structure. josephus(n, k) = (josephus(n – 1, k) + k-1) % n + 1 and josephus(1, k) = 1 After the first person (kth from the beginning) is killed, n-1 persons are left. Make recursive call for Josephus(n – 1, k) to get the position with n-1 persons. But the position returned by Josephus(n – 1, k) will consider the position starting from k%n + 1. So make adjustments to the position returned by Josephus(n – 1, k).

Below is the Implementation of the above idea.

Time Complexity: O(N) Auxiliary Space: O(N) the space used in recursion call stack

Please visit set-2: Josephus problem | Set 2 (A Simple Solution when k = 2)

Source: http://en.wikipedia.org/wiki/Josephus_problem Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

## Josephus Problem using Queue :

I am using queue data structure, so that i can move the items from one end to another linearly. we have given ‘K’ the moves we can shift, so after shifting K-1 items to the end of the queue, I am deleting the front element. On repeating the above step, a stage will come when only one element will be left, this is answer itself.

Time Complexity: O(N*K) Space Complexity: O(N)

- DSA in Java
- DSA in Python
- DSA in JavaScript

## Please Login to comment...

- Akanksha_Rai
- RiteshYadav7
- SHUBHAMSINGH10
- hritikrommie
- sameerhakeentc2019
- divyesh072019
- shishankrawt93774
- rameshtravel07
- umadevi9616
- surinderdawra388
- surindertarika1234
- sumitgumber28
- qwcllh9fr90rljmmxnhnev0o49esfddve93ojc2o
- kandelgaurav7
- yashagarwal2852002
- sarveshc111
- harendrakumar123
- aashutoshparoha
- spiralforge3008
- aksh_mangal
- esrinivasa7kps
- akshitaguprzj3

Please write us at contrib[email protected] to report any issue with the above content

## Improve your Coding Skills with Practice

## Josephus Problem Using an Array in C

The obvious data structure to use in this problem is a circular linked list. But the book, Algorithms in C, asks you to do it with an array. Here’s my implementation.

https://github.com/scottmurs/C_Programs/blob/master/algorithms_in_c/3-4.c

/* * ===================================================================================== * * Filename: 3-4.c * * Description: write a program to solve the Josephus problem, using an array * instead of a linked list * * Version: 1.0 * Created: 01/03/2018 03:28:13 AM * Revision: none * Compiler: gcc * * Author: scott myers * Organization: * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> #define N 10 void init_arr(void); // initialize the array with N members void execute(int n); // execute the nth member starting and index start int len_arr(void); // return the length of the array void reorder_arr(void); // reorder the array such that the member at index n is removed void print_arr(void); static int arr[N]; static int len = N, start = 0; int main(void) { // init array init_arr(); while (len_arr() > 1) { print_arr(); // execute one execute(5); // rebuild array reorder_arr(); } // print remaining member print_arr(); return 0; } void init_arr(void) { for (int i = 0; i < N; i++) arr[i] = i; } void execute(int n) { int i; i = (start + n-1) % len; arr[i] = -1; start = i; } int len_arr(void) { return len; } void reorder_arr(void) { int i; // find index with value == 0 for (i = 0; i < len && arr[i] != -1; i++) ; // copy i+1 into i until i == len for (i++; i < len; i++) arr[i-1] = arr[i]; // decrement len len--; } void print_arr(void) { printf("len: %d\n", len); for (int i = 0; i < len; i++) printf("%d ", arr[i]); printf("\n"); }

@ scottmyers / scottmyers.tumblr.com

## Roy Tutorials

Technical… Theoretical… Practical…

## How to Solve Josephus Problem using Pointer in C program

Introduction.

You will see how to solve Josephus problem using pointer in C program. So, I am going to use C program as well as pointer to solve Josephus problem.

The Josephus problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game. The problem is described as below.

People are standing in a circle waiting to be executed. Counting begins at a specified point in the circle and proceeds around the circle in a specified direction. After a specified number of people are skipped, the next person is executed.

The procedure is repeated with the remaining people, starting with the next person, going in the same direction and skipping the same number of people, until only one person remains, and is freed.

Related Posts:

- Solving Josephus problem using PHP
- Solving Josephus problem using Java
- Solving Josephus Problem using Python c

## Implementation of Josephus Problem

The implementation of Josephus problem is given below using C program and pointer.

The n is the number of persons or people in the circle and k is the start position of execution.

## Testing the Program

By executing the above C program you will get the following output:

## Ananlysis of the Logic

Let’s take an example of there are 5 people in a circle and execution starts clockwise at position 3, so I will find out the winner of the game.

So there are five people – 1 2 3 4 5 and execution starts clockwise at position 3. Therefore if you kill 3 then are left with the list something like – 1 2 4 5.

Now again, you want to kill the person at position 3 clockwise counting from the last killed person.

Now, you need to execute the person at position 1. So executing the person at 1, you are left with the list 2 4 5. After executing another person, you get list 2 4.

Now, you are left with 2 persons in the list. So, you have to calculate the position wisely to execute the person.

So finally the winner is 4.

## Source Code

Leave a reply cancel reply.

Your email address will not be published. Required fields are marked *

Copyright © 2023 Roy Tutorials

## Easy Josephus problem solution using Circular Linked List

- Post author: CodeEasy
- Post published: October 5, 2023
- Post comments: 0 Comments

## Josephus Problem Solution Code

This code is for implementing Josephus Problem using Circular Linked List. Actually Josephus problem is a concept of deleting node on counter basis.

If you take a counter of 3 for performing this problem then it will start by deleting the 3rd node starting from the head node, then and after the victim node(3rd node) will be counted from the next node of the last deleted node.

This process will be continuing until a single node is remaining.

For Such more codes click here and for video tutorial click here .

## You Might Also Like

How to calculate area and perimeter of a triangle.

## Easy Bubble Sort Using Linked List Code

## Easy Diamond of Star printing solution in 2023

Leave a reply cancel reply.

Save my name, email, and website in this browser for the next time I comment.

Search anything:

## Josephus Problem

Get FREE domain for 1st year and build your brand new site

## Algorithms List of Mathematical Algorithms

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have explored and solved Josephus Problem in depth which is a Standard Problem in Computer Science. We have presented two solutions to Josephus Problem.

Table of contents:

## Introduction to Josephus Problem

Solving the josephus problem, implementation of recursive solution, an alternative solution.

The Josephus Problem is a theoretical problem in computer science and mathematics, where people standing in a circle get executed one-by-one until one person remains. A person at a specified position starts counting, and this counting proceeds in one direction, until it reaches a pre-fixed number, after which the person standing next in the circle gets executed. The counting restarts from the next person, and this process continues until all but one person remains.

The problem is usually stated in terms of the number of persons standing in the circle (n), and a number k, which denotes that the kth person will be executed on counting.

We shall first consider a toy case, where n = 7, and k = 2.

First, since 1 starts the counting and the kth person gets executed, 2 gets executed.

Now, since 3 starts counting, 4 gets executed, and in a similar manner 6 also gets executed once 5 starts counting.

Now, since it is 7 who starts counting, 1 gets executed. Now the count goes to 3, and 5 gets executed.

Since 7 is the only person remaining, he wins.

Let us denoted the Josephus problem with n people and k counts as J(n,k). We first observe the following:

- The problem eliminates one person at a time until 1 person remains.
- Let the position of the person who starts counting be i. Then the person executed would be (i+ (k-1))(mod n) Here, we add k-1 since the counting starts from and includes the ith person. Also, we obtain the remainder modulo n since after the last person counts, it would once again be the first person in the circle who continues the count. In this case, the position of the person who starts counting next would be (i + (k-1))(mod n) + 1.
- After the first person gets executed, J(n,k) gets reduced to J(n-1, k), but the start position in this case becomes (1 + k - 1)(mod n) + 1.
- When the problem is J(1,k), then only one person remains, and hence J(1,k) = 1.

Hence, we can observe that J(n,k) can be broken down into smaller subproblems, and can therefore be solved recursively. We define the recursive relation as follows:

Since this recursive call runs exactly n times, and since the number of calls does not depend on k, the time complexity of this solution is given by O(n) . The space complexity is also O(n) , since each recursion takes O(1) space, and the total number of recursions is n.

Toy Case Revisited

We now try to solve J(7,2) using the recursive formula dervied earlier. We shall work backwards from J(1,2). Now, J(1,2) = 1 J(2,2) = [J(1,2) + 1](mod 2) + 1 = 1 J(3,2) = [J(2,2) + 1](mod 3) + 1 = 3 J(4,2) = [J(3,2) + 1](mod 4) + 1 = 1 J(5,2) = [J(4,2) + 1](mod 5) + 1 = 3 J(6,2) = [J(5,2) + 1](mod 6) + 1 = 5 J(7,2) = [J(6,2) + 1](mod 7) + 1 = 7

Hence, we have obtained the same solution as earlier.

We shall now implement this using C++.

Here, we observe that J(10,4) = 5, which can be verified manually.

Although the recursive solution is efficient, there is always a chance of stack overflow, since it may need a lot of memory to hold the intermediate solutions. This problem can be resolved with an iterative implementation of the same solution. In this method, we shall work backwards from the case where there are only two people. We calculate the position of the winner in each case, and thus determine the winner for the given scenario. Note that the logic here is the same as that of the recursive solution.

Since this iterative loop shall run n-1 times, it's time complexity is given by O(n) , the same as the recursive solution. However, the space complexity is O(1) , since the loop does not need any extra memory.

Implementation of Iterative Solution

With this article at OpenGenus, you must have the complete idea of Josephus Problem.

- 15 Puzzle Game: Existence Of The Solution
- The Stern-Brocot Tree and Farey Sequences

## Josephus Problem ¶

Statement ¶.

We are given the natural numbers $n$ and $k$ . All natural numbers from $1$ to $n$ are written in a circle. First, count the $k$ -th number starting from the first one and delete it. Then $k$ numbers are counted starting from the next one and the $k$ -th one is removed again, and so on. The process stops when one number remains. It is required to find the last number.

This task was set by Flavius Josephus in the 1st century (though in a somewhat narrower formulation: for $k = 2$ ).

This problem can be solved by modeling the procedure. Brute force modeling will work $O(n^{2})$ . Using a Segment Tree , we can improve it to $O(n \log n)$ . We want something better though.

## Modeling a $O(n)$ solution ¶

We will try to find a pattern expressing the answer for the problem $J_{n, k}$ through the solution of the previous problems.

Using brute force modeling we can construct a table of values, for example, the following:

And here we can clearly see the following pattern :

Here, 1-indexing makes for a somewhat messy formula; if you instead number the positions from 0, you get a very elegant formula:

So, we found a solution to the problem of Josephus, working in $O(n)$ operations.

## Implementation ¶

Simple recursive implementation (in 1-indexing)

Non-recursive form :

This formula can also be found analytically. Again here we assume 0-indexing. After we delete the first number, we have $n-1$ numbers left. When we repeat the procedure, we will start with the number that had originally the index $k \bmod n$ . $J_{n-1, k}$ would be the answer for the remaining circle, if we start counting at $0$ , but because we actually start with $k$ we have $J_{n, k} = (J_{n-1,k} + k) \ \bmod n$ .

## Modeling a $O(k \log n)$ solution ¶

For relatively small $k$ we can come up with a better solution than the above recursive solution in $O(n)$ . If $k$ is a lot smaller than $n$ , then we can delete multiple numbers ( $\lfloor \frac{n}{k} \rfloor$ ) in one run without looping over. Afterwards we have $n - \lfloor \frac{n}{k} \rfloor$ numbers left, and we start with the $(\lfloor \frac{n}{k} \rfloor \cdot k)$ -th number. So we have to shift by that many. We can notice that $\lfloor \frac{n}{k} \rfloor \cdot k$ is simply $-n \bmod k$ . And because we removed every $k$ -th number, we have to add the number of numbers that we removed before the result index. Which we can compute by dividing the result index by $k - 1$ .

Also, we need to handle the case when $n$ becomes less than $k$ . In this case, the above optimization would cause an infinite loop.

Implementation (for convenience in 0-indexing):

Let us estimate the complexity of this algorithm. Immediately note that the case $n < k$ is analyzed by the old solution, which will work in this case for $O(k)$ . Now consider the algorithm itself. In fact, after every iteration, instead of $n$ numbers, we are left with $n \left( 1 - \frac{1}{k} \right)$ numbers, so the total number of iterations $x$ of the algorithm can be found roughly from the following equation:

on taking logarithm on both sides, we obtain:

using the decomposition of the logarithm into Taylor series, we obtain an approximate estimate:

Thus, the complexity of the algorithm is actually $O (k \log n)$ .

## Analytical solution for $k = 2$ ¶

In this particular case (in which this task was set by Josephus Flavius) the problem is solved much easier.

In the case of even $n$ we get that all even numbers will be crossed out, and then there will be a problem remaining for $\frac{n}{2}$ , then the answer for $n$ will be obtained from the answer for $\frac{n}{2}$ by multiplying by two and subtracting one (by shifting positions):

Similarly, in the case of an odd $n$ , all even numbers will be crossed out, then the first number, and the problem for $\frac{n-1}{2}$ will remain, and taking into account the shift of positions, we obtain the second formula:

We can use this recurrent dependency directly in our implementation. This pattern can be translated into another form: $J_{n, 2}$ represents a sequence of all odd numbers, "restarting" from one whenever $n$ turns out to be a power of two. This can be written as a single formula:

## Analytical solution for $k > 2$ ¶

Despite the simple form of the problem and a large number of articles on this and related problems, a simple analytical representation of the solution of Josephus' problem has not yet been found. For small $k$ , some formulas are derived, but apparently they are all difficult to apply in practice (for example, see Halbeisen, Hungerbuhler "The Josephus Problem" and Odlyzko, Wilf "Functional iteration and the Josephus problem").

- singamandeep (63.09%)
- jakobkogler (17.45%)
- AbhijeetKrishnan (12.75%)
- adamant-pwn (4.7%)
- algmyr (1.34%)
- diksown (0.67%)

## IMAGES

## VIDEO

## COMMENTS

A variety of solutions for environmental problems exist including recycling, reduction of carbon emissions from fossil fuels, finding alternative energy solutions and the conservation of marine life.

Two examples of probability and statistics problems include finding the probability of outcomes from a single dice roll and the mean of outcomes from a series of dice rolls. The most-basic example of a simple probability problem is the clas...

Sexually transmitted infections and unwanted pregnancies can be partly solved by comprehensive sex education. Job creation and work support are some solutions to hunger and poverty. Social support and access to health care are some solution...

Array implementation of the josephus problem */ #include <stdio.h> #define SENTINEL -1 int main() { int M, N, i, count = 0, steps, arr[100]; scanf("%d %d"

Approach to solve Josephus problem iteratively: · Initialize variables num, cnt, and cut with 1, 0, and 0 respectively and an array arr[] of size

how so an infinite loop? the game is to count the prisoners, and kill the next one, so for 10 and 2, the third one dies, the 6th guy dies, the

Josephus Problem Using an Array in C. The obvious data structure to use in this problem is a circular linked list. But the book, Algorithms

Algorithm · Create an array arr[] of size N with the initial value set to 1, and initialize the variables: size, start, and end with the values 1

Josephus algorithm using array in C#, Explanation for recursive implementation of Josephus problem, Josephus Algorithm Glitch using a

Josephus Problem talks about a problem where there are people standing in a circle waiting to be executed. The counting out begins at some point in the circle

The implementation of Josephus problem is given below using C program and pointer. The n is the number of persons or people in the circle and k is the start

This code is for implementing Josephus Problem using Circular Linked List and is a concept of deleting node on counter basis.

Implementation of Recursive Solution. We shall now implement this using C++. #include<iostream> using namespace

Using brute force modeling we can construct a table of values, for ... solution of Josephus' problem has not yet been found. For small k