From 2d9ec841fa2f23fe9319feafde8640c392a5947a Mon Sep 17 00:00:00 2001 From: Pranav-Rustagi Date: Thu, 20 Oct 2022 19:03:46 +0530 Subject: [PATCH] Added algorithm for Josephus problem --- algorithms/CPlusPlus/README.md | 1 + .../CPlusPlus/Recursion/josephus-problem.cpp | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 algorithms/CPlusPlus/Recursion/josephus-problem.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 8b3d72ed..4d3ffbd9 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -201,6 +201,7 @@ - [Product of digits in a number](Recursion\product-of-digits.cpp) - [Linear search using recursion](Recursion/linear-search.cpp) - [Reverse a number using recursion](Recursion/reverse-a-number.cpp) +- [Josephus problem](Recursion/josephus-problem.cpp) ## Number System diff --git a/algorithms/CPlusPlus/Recursion/josephus-problem.cpp b/algorithms/CPlusPlus/Recursion/josephus-problem.cpp new file mode 100644 index 00000000..bafe985c --- /dev/null +++ b/algorithms/CPlusPlus/Recursion/josephus-problem.cpp @@ -0,0 +1,19 @@ +#include +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 \ No newline at end of file