Person left at the end

By | December 12, 2022

Given the value of N which represents the number of people standing in the queue, Each person has an id equivalent to their position. Now from this queue, the people who are at even locations are removed and made a separate queue. This process continues till 1 person left. The task is to determine the id of the person who left at the last.

Examples :

Input : N = 5 
Output : 4
(queue = 1 2 3 4 5
after 1st operation = 2 4
after 2nd operation = 4)

Input : N = 8
Output : 8

Approach :

  1. Take the floor of the log to the base 2 of the total number of the person in the queue. And store it in any variable say result.
  2. Now, calculate power(2, result). This is our answer.

Implementation of the above program :

// #include<bits/stdc++.h>
#include<iostream>
using namespace std;

// Function that will
// tell the id of the person left
int Number(int n)
{
    int result = 0;
    
    result = pow(2, floor(log2(n)));
    
    return result;
}

// Driver code
int main()
{
    int N = 5;
    
    // Calling function
    cout<<Number(N);
    
    return 0;
}

Output :

4

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.