Solution of 10940 - Throwing cards away II

Problem Description
source:https://uva.onlinejudge.org/external/109/10940.html


Given is an ordered deck of n cards numbered 1 to n with card 1 at the top and card n at the bottom. The following operation is performed as long as there are at least two cards in the deck: 
     Throw away the top card and move the card that is now on the top of the deck to the bottom of the deck. 
     Your task is to find the last, remaining card. 

Input 

Each line of input (except the last) contains a positive number n ≤ 500000. The last line contains ‘0’ and this line should not be processed. Input will not contain more than 500000 lines

Output 

For each number from input produce one line of output giving the last remaining card. 

Sample Input 


19 
10 



Sample Output 




4

Solution:
#include<stdio.h>
int main()
{
    long int n,i,mod,result;
    while(scanf("%ld",&n)==1 && n!=0)
    {
        i=1;
        while(i<=n)
        {
            i=i*2;
        }
        mod=i%n;
        result=n-mod;
        printf("%ld\n",result);
    }
    return 0;
}

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience