-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathjosephusProblem.cpp
28 lines (23 loc) · 1.08 KB
/
josephusProblem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Josephus Problem
/*It is a basic and important problem of recursion.
The problem is explained here-
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.
*/
#include <bits/stdc++.h>
using namespace std;
int josephus(int n, int k)
{
if (n == 1)
return 1;
else
return (josephus(n - 1, k) + k-1) % n + 1;
}
int main()
{
int n;
cin>>n;
int k;
cin>>k;
cout << "The chosen place is " << josephus(n, k);
return 0;
}