Question #238642

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 sequence of discarded cards and the last, remaining card.
Each line of input (except the last) contains a number 2 ≤ n ≤ 52. The last line contains 0 and this line
should not be processed.
Sample:
Input:
7
19
2
0
Output:
Discarded cards: 1, 3, 5, 7, 4, 2,
Remaining card: 6
Discarded cards: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 4, 8, 12, 16, 2, 10, 18, 14,
Remaining card: 6
Discarded cards: 1,
Remaining card: 2

Expert's answer

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring>




#define N 10001
using namespace std;
int arr[N],l,p,num,x;
bool b;
int main()
{
    scanf("%d",&num);
    while(num!=0)
    {
        memset(arr,0,sizeof(arr));
        for(int i=1;i<=num;i++) arr[i]=i;
        l=1; 
        p=num;
        b=0;
        x=0;
        printf("Discarded cards:");
        while(l<p)
        {
            if(b==0)
            {
                printf(" %d",arr[l]);
                l++;
                x++;
                if(x<num-1) printf(",");
                b=1;
            } else
            {
                p++;
                arr[p]=arr[l];
                l++;
                b=0;
            }
        }
        printf("\n");
        printf("Remaining card: %d\n",arr[l]);
        scanf("%d",&num);
    }
    return 0;
}

LATEST TUTORIALS
APPROVED BY CLIENTS