/ Assignment / assignment_27.java
assignment_27.java
 1  /* 
 2   * This program finds the luckiest number in a circular elimination game.
 3   * Each number shoots the next one in sequence until only one remains.
 4   * For example: 1 shoots 2, 3 shoots 4, and so on.
 5   */
 6  
 7  import java.util.Scanner; // Import Scanner class to take user input
 8  
 9  public class assignment_27 { // Define the class
10  
11      /**
12       * Method to calculate the luckiest number based on the Josephus problem (special case).
13       * The logic follows:
14       * 1. Find the largest power of 2 less than or equal to `n`
15       * 2. Compute the remainder after subtracting this power of 2 from `n`
16       * 3. Use the formula `2 * remainder + 1` to determine the last remaining number
17       */
18      public static long luckiestNumber(long n) {
19          // Find the highest power of 2 less than or equal to `n`
20          int m = (int) Math.floor(Math.log(n) / Math.log(2));
21  
22          // Compute the power of 2 using exponentiation
23          long powerOfTwo = (long) Math.pow(2, m);
24  
25          // Compute the remainder when `n` is reduced by the highest power of 2
26          long remainder = n - powerOfTwo;
27  
28          // Apply the formula to find the luckiest number
29          long luckiest = 2 * remainder + 1;
30  
31          return luckiest; // Return the result
32      }
33  
34      public static void main(String[] args) {
35          Scanner sc = new Scanner(System.in); // Create Scanner object to read input
36  
37          // Prompt user to enter the total number of people
38          System.out.print("Enter the number of people in the circle: ");
39          long n = sc.nextLong(); // Read integer input
40  
41          try {
42              // Compute the luckiest number using the method
43              long result = luckiestNumber(n);
44  
45              // Print the luckiest number
46              System.out.println("Luckiest Number is: " + result);
47          } catch (IllegalArgumentException e) {
48              // Handle exceptions and display error message
49              System.err.println(e);
50          }
51  
52          sc.close(); // Close the scanner to prevent resource leaks
53      }
54  }