Solving Josephus problem using Java

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

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.

For more information you can read

The source code example is given below

package com.test;

import java.util.List;

public class JosephProblem {

	public static void main(String[] args) {
		int winner = joseph(5, 3);
		System.out.println("winner is " + winner);
		winner = joseph(10, 3);
		System.out.println("winner is " + winner);
		winner = joseph(5, 2);
		System.out.println("winner is " + winner);
		winner = joseph(7, 3);
		System.out.println("winner is " + winner);

	public static int joseph(int noOfPeople, int remPosition) {
		int tempPos = remPosition - 1;
		int[] people = new int[noOfPeople];
		for (int i = 0; i < noOfPeople; i++) {
			people[i] = i + 1;

		int iteration = noOfPeople - 1;
		List<Integer> list = IntStream.of(people).boxed().collect(Collectors.toList());
		while (iteration > 0) {
			tempPos += remPosition - 1;
			if (tempPos > list.size() - 1) {
				tempPos = tempPos % list.size();
		return list.get(0);


Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Twitter Facebook  Google Plus Linkedin

Leave a Reply

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