From 26f177a32b860afb41018e00f8c6a6326999352c Mon Sep 17 00:00:00 2001 From: Priya Agrawal Date: Sat, 9 Oct 2021 21:26:08 +0530 Subject: [PATCH] Josephus Problem.cpp --- recursion/c++/#include .cpp | 24 ++++++++++++++++++++++++ recursion/c++/Josephus Problem.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 recursion/c++/#include .cpp create mode 100644 recursion/c++/Josephus Problem.cpp diff --git a/recursion/c++/#include .cpp b/recursion/c++/#include .cpp new file mode 100644 index 0000000..fe6d54a --- /dev/null +++ b/recursion/c++/#include .cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + +int josephus(int n, int k) +{ + if (n == 1) + return 1; + else + /* The position returned by josephus(n - 1, k) + is adjusted because the recursive call + josephus(n - 1, k) considers the + original position k % n + 1 as position 1 */ + return (josephus(n - 1, k) + k - 1) % n + 1; +} + +// Driver Program to test above function +int main() +{ + int n = 14; + int k = 2; + cout << "The chosen place is " << josephus(n, k); + return 0; +} + diff --git a/recursion/c++/Josephus Problem.cpp b/recursion/c++/Josephus Problem.cpp new file mode 100644 index 0000000..fe6d54a --- /dev/null +++ b/recursion/c++/Josephus Problem.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + +int josephus(int n, int k) +{ + if (n == 1) + return 1; + else + /* The position returned by josephus(n - 1, k) + is adjusted because the recursive call + josephus(n - 1, k) considers the + original position k % n + 1 as position 1 */ + return (josephus(n - 1, k) + k - 1) % n + 1; +} + +// Driver Program to test above function +int main() +{ + int n = 14; + int k = 2; + cout << "The chosen place is " << josephus(n, k); + return 0; +} +