Skip to content

Commit f2208d6

Browse files
committed
Adding Josephus Algorithm
1 parent 546d270 commit f2208d6

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Author : Sundar
2+
3+
/*Problem : N people are standing in a circle and we continuously eliminate the M th person
4+
starting from the first. Find the peson who is not eliminated and is still standing in the circle
5+
6+
Sample Input: 5 2
7+
Ans : 3
8+
The 3rd person is the person who is not eliminated.
9+
*/
10+
11+
#include<iostream>
12+
using namespace std;
13+
int josephus_iterative(int N,int M)
14+
{
15+
int res=0;
16+
for(int i=1;i<=N;i++)
17+
{
18+
res=(res+M)%i;
19+
}
20+
return res+1;
21+
}
22+
int josephus_recursive(int N,int M)
23+
{
24+
if(N==1)
25+
return 1;
26+
int a=josephus_recursive(N-1,M);
27+
return (a+M-1)%N+1;
28+
}
29+
30+
31+
32+
int main()
33+
{
34+
int N,M;
35+
//N - number of people in the circle
36+
//M - people from the current location to be eliminated
37+
cin>>N>>M;
38+
39+
40+
cout<<"The Last Standing person derived using ITERATION : "<<josephus_iterative(N,M)<<'\n';
41+
cout<<"The Last Standing person derived using RECURSION : "<<josephus_recursive(N,M)<<'\n';
42+
return 0;
43+
}

0 commit comments

Comments
 (0)