Skip to content

Commit 7d544da

Browse files
committed
Add Josephus Problem in C++ (Fixes #3332)
1 parent 3501866 commit 7d544da

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
int josephus(int n, int k) {
6+
int res = 0;
7+
for (int i = 1; i <= n; i++)
8+
res = (res + k) % i;
9+
return res + 1;
10+
}
11+
12+
int main(int argc, char* argv[]) {
13+
if (argc != 3) {
14+
cerr << "Usage: <n> <k>" << endl;
15+
return 1;
16+
}
17+
18+
int n = stoi(argv[1]);
19+
int k = stoi(argv[2]);
20+
if (n <= 0 || k <= 0) {
21+
cerr << "Invalid input" << endl;
22+
return 1;
23+
}
24+
25+
cout << josephus(n, k) << endl;
26+
return 0;
27+
}

0 commit comments

Comments
 (0)