Josephus Problem | Recursion | Java

There are N people standing in a circle numbered from 1 to N. Also given an integer K. 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. The task is to find the last number.

Examples:

Input: N = 6, K = 2
Output: 5

image

Java solution using recursion :

public class JosephusProblem {

	public static void main(String[] args) {
		  
		        
		        List<Integer> winner = new ArrayList<>();
		        int i = 1;
		        while(i <= 5){
		            winner.add(i);
		            i++;
		        }
		        
		       int t = findWinner(winner,5  , 1 , 0);
		       System.out.println(t);
		    
	}

	

    public static  int findWinner(List<Integer> w,int n ,int k, int start){
        
        if( n == 1){
         return w.get(0); 
        }
        
        int i = (start+k)%n;
        w.remove(i);
        n--;
         return findWinner(w , n , k ,i);
        
    }
}
Comments (0)