Added algorithm for Josephus problem
parent
c2f2a4cb20
commit
2d9ec841fa
|
@ -201,6 +201,7 @@
|
||||||
- [Product of digits in a number](Recursion\product-of-digits.cpp)
|
- [Product of digits in a number](Recursion\product-of-digits.cpp)
|
||||||
- [Linear search using recursion](Recursion/linear-search.cpp)
|
- [Linear search using recursion](Recursion/linear-search.cpp)
|
||||||
- [Reverse a number using recursion](Recursion/reverse-a-number.cpp)
|
- [Reverse a number using recursion](Recursion/reverse-a-number.cpp)
|
||||||
|
- [Josephus problem](Recursion/josephus-problem.cpp)
|
||||||
|
|
||||||
## Number System
|
## Number System
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,19 @@
|
||||||
|
#include <bits/stdc++.h>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
int josephus(int n, int k) {
|
||||||
|
if(n == 1)
|
||||||
|
return 1;
|
||||||
|
return (josephus(n - 1, k) + k - 1) % n + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n, k;
|
||||||
|
cin >> n >> k;
|
||||||
|
cout << josephus(n, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Space Complexity: O(n)
|
||||||
|
// Time Complexity: O(n)
|
||||||
|
// Input: 3 2
|
||||||
|
// Output: 3
|
Loading…
Reference in New Issue