Algorithm


problem Link  : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1715 

No, I don’t want you to waste important time reading boring introduction. At first, there are n people numbered 1 to n around a circle and every second remaining person will be eliminated until only one survives. Let the number of the survivor be x. The process is then repeated with x number of people and let the survivor number is y. The process then starts with y number of people and so on. The repetition ends when the survivor is in the last position in the circle. Example with n = 5: After the first elimination round, the survivor is person 3. Because this is is not the last person in the circle, a new elimination round with 3 people is started. Now person 3 survives, so we can stop. Input The first line in the input file is an integer representing the number of test cases. Each of the test cases follows below. Each test case consists of an integer representing n (0 < n ≤ 30000). Output For each test case, print the serial number of the case, a colon, an space, total number of repetitions (the number of times the elimination process is done after the initial elimination round with n people), an space and the position of the survivor at last. Check the sample input & output.

Sample Input 2 13 23403

Sample Output Case 1: 2 7 Case 2: 8 1023

Code Examples

#1 Code Example with C Programming

Code - C Programming

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

// get last survivor of josephus iteration
int josephus(int n, int k) {
    int s = 0;
    for(int i=2;i < =n;i++)
        s = (s+k)%i; // next person after the one that is killed
    return s+1;
}

int main() {
    int t,n;
    scanf("%d",&t);
    for(int tc=1;tc < =t;tc++) {
        scanf("%d",&n);
        int iteration = 0;
        while(1) {
            int survive = josephus(n, 2);
            iteration++;
            if(survive == n) break;
            n = survive;
        }
        printf("Case %d: %d %d\n", tc, iteration-1, n);
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
2
13
23403

Output

x
+
cmd
Case 1: 2 7
Case 2: 8 1023
Advertisements

Demonstration


UVA Online Judge solution - 10774-Repeated Josephus  - UVA Online Judge solution in C,C++,java

Previous
UVA Online Judge solution - 10765-Doves and bombs - UVA Online Judge solution in C,C++,java
Next
UVA Online Judge solution - 10785-The Mad Numerologist - UVA Online Judge solution in C,C++,java