Skip to content

Commit 3a750ee

Browse files
committed
Josephus Problem for recursion
1 parent 162dfa4 commit 3a750ee

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

josephusProblem.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//Josephus Problem
2+
/*It is a basic and important problem of recursion.
3+
The problem is explained here-
4+
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.
5+
*/
6+
7+
8+
#include <bits/stdc++.h>
9+
using namespace std;
10+
11+
int josephus(int n, int k)
12+
{
13+
if (n == 1)
14+
return 1;
15+
else
16+
17+
return (josephus(n - 1, k) + k-1) % n + 1;
18+
}
19+
20+
int main()
21+
{
22+
int n;
23+
cin>>n;
24+
int k;
25+
cin>>k;
26+
cout << "The chosen place is " << josephus(n, k);
27+
return 0;
28+
}

0 commit comments

Comments
 (0)