class Clever_prisoner { // The following function computes the position of the prisoner // who will be executed on the first day when there are n prisoners // in the row and the selection-number is m public static int The_Unlucky_Position(int m, int n) { if(m%n==0) return n; else return m%n; } public static void main(String args[]) { int Total_number_of_prisoners = Integer.parseInt(args[0]); int m = Integer.parseInt(args[1]); //We are going to compute the solution in bottom up fashion //So for the bottom/base case, we set position_of_clever_prisoner //as 1 since he/she escapes execution. int position_of_clever_prisoner=1; //We initialize the number of prisoners to 2 and gradually //increase the number upto The Total number of prisoners //and compute position of the clever prisoner incrementally //in the while loop. int number_of_prisoners = 2; while(number_of_prisoners<=Total_number_of_prisoners) { int unlucky_position = The_Unlucky_Position(m,number_of_prisoners); if(unlucky_position <= position_of_clever_prisoner) position_of_clever_prisoner = position_of_clever_prisoner+1; number_of_prisoners=number_of_prisoners+1; } System.out.print("The Total number of prisoners is = "); System.out.println(Total_number_of_prisoners); System.out.println("The selection number m is ="+m); System.out.print("The position of clever prisoner = "); System.out.println(position_of_clever_prisoner); } }