Skip to content

Commit f9cb14f

Browse files
authored
Merge pull request #341 from riyavaryani/master
Josephus Problem for recursion
2 parents dab8de7 + 05440f3 commit f9cb14f

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

fibonacci_xor.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//Fibonacci XOR
2+
/*You are given three integers a, b, and n, calculate f(n), where f(n) is the xor of last two numbers
3+
i.e, f(n) = f(n-1)?f(n-2), where ? is xor operation.
4+
*/
5+
6+
7+
#include<bits/stdc++.h>
8+
using namespace std;
9+
int main()
10+
{
11+
int a,b,n;
12+
13+
cin>>a>>b>>n;
14+
int rem=n%3;
15+
if(rem==0) cout<<a<<endl;
16+
else if(rem==1) cout<<b<<endl;
17+
else cout<<(a^b)<<endl;
18+
19+
return 0;
20+
}
21+

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)