Skip to content

Commit 7c8815a

Browse files
committed
Fix: Simplify output format for Josephus Problem to match test requirements
1 parent 7d544da commit 7c8815a

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed
Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
#include <iostream>
2-
#include <vector>
2+
#include <stdexcept>
33
using namespace std;
44

55
int josephus(int n, int k) {
66
int res = 0;
7-
for (int i = 1; i <= n; i++)
7+
for (int i = 1; i <= n; ++i) {
88
res = (res + k) % i;
9+
}
910
return res + 1;
1011
}
1112

@@ -15,13 +16,23 @@ int main(int argc, char* argv[]) {
1516
return 1;
1617
}
1718

18-
int n = stoi(argv[1]);
19-
int k = stoi(argv[2]);
20-
if (n <= 0 || k <= 0) {
19+
try {
20+
int n = stoi(argv[1]);
21+
int k = stoi(argv[2]);
22+
23+
if (n <= 0 || k <= 0) {
24+
cerr << "Invalid input" << endl;
25+
return 1;
26+
}
27+
28+
cout << josephus(n, k) << endl;
29+
return 0;
30+
31+
} catch (const invalid_argument&) {
32+
cerr << "Invalid input" << endl;
33+
return 1;
34+
} catch (const out_of_range&) {
2135
cerr << "Invalid input" << endl;
2236
return 1;
2337
}
24-
25-
cout << josephus(n, k) << endl;
26-
return 0;
2738
}

0 commit comments

Comments
 (0)