Skip to content

Commit 21d183b

Browse files
authored
Add Josephus Problem in Java (Fixes #3345) (#5165)
1 parent 962003e commit 21d183b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.*;
2+
3+
public class JosephusProblem {
4+
5+
private static int josephus(int n, int k) {
6+
if (n == 1) return 1;
7+
return (josephus(n - 1, k) + k - 1) % n + 1;
8+
}
9+
10+
public static void main(String[] args) {
11+
final String usage_msg = "Usage: please input the total number of people and number of people to skip.\n";
12+
13+
if (args.length != 2) {
14+
System.err.print(usage_msg);
15+
System.exit(1);
16+
}
17+
18+
int n=0, k=0;
19+
try {
20+
n = Integer.parseInt(args[0]);
21+
k = Integer.parseInt(args[1]);
22+
} catch (NumberFormatException e) {
23+
System.err.print(usage_msg);
24+
System.exit(1);
25+
}
26+
27+
if (n <= 0 || k <= 0) {
28+
System.err.print(usage_msg);
29+
System.exit(1);
30+
}
31+
32+
int result = josephus(n, k);
33+
System.out.println(result);
34+
}
35+
}

0 commit comments

Comments
 (0)