-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathjosephus problem
More file actions
30 lines (26 loc) · 893 Bytes
/
josephus problem
File metadata and controls
30 lines (26 loc) · 893 Bytes
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
29
30
// 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 in a fixed direction.
// The task is to choose the safe place in the circle so that when you perform these operations starting from 1st place in the circle, you are the last one remaining and survive.
// Example 1:
// Input:
// n = 3 k = 2
// Output: 3
#include <iostream>
using namespace std;
int josephus(int n, int k)
{
if (n == 1)
return 1;
else
/* The position returned by josephus(n - 1, k)
is adjusted because the recursive call
josephus(n - 1, k) considers the
original position k % n + 1 as position 1 */
return (josephus(n - 1, k) + k-1) % n + 1;
}
int main()
{
int n = 14;
int k = 2;
cout << "The chosen place is " << josephus(n, k);
return 0;
}