-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathJosephus_problem.cpp
More file actions
59 lines (55 loc) · 1.25 KB
/
Copy pathJosephus_problem.cpp
File metadata and controls
59 lines (55 loc) · 1.25 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
int Josephus(int, int);
int main()
{
int n, k;
cin >> n >> k;
cout << Josephus(n, k);
return 0;
}
int Josephus(int n, int k)
{
k--;
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = 1; // Makes all the 'n' people alive by
// assigning them value = 1
}
int cnt = 0, cut = 0,
num = 1; // Cut = 0 gives the sword to 1st person.
while (
cnt
< (n - 1)) // Loop continues till n-1 person dies.
{
while (num <= k) // Checks next (kth) alive persons.
{
cut++;
cut = cut % n; // Checks and resolves overflow
// of Index.
if (arr[cut] == 1) {
num++; // Updates the number of persons
// alive.
}
}
num = 1; // refreshes value to 1 for next use.
arr[cut]
= 0; // Kills the person at position of 'cut'
cnt++; // Updates the no. of killed persons.
cut++;
cut = cut
% n; // Checks and resolves overflow of Index.
while (arr[cut]
== 0) // Checks the next alive person the
// sword is to be given.
{
cut++;
cut = cut % n; // Checks and resolves overflow
// of Index.
}
}
return cut + 1; // Output is the position of the last
// man alive(Index + 1);
}
/********************THIS CODE IS PRESENTED BY SHISHANK
* RAWAT**************************/