Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions archive/j/java/JosephusProblem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.*;

public class JosephusProblem {

private static int josephus(int n, int k) {
if (n == 1) return 1;
return (josephus(n - 1, k) + k - 1) % n + 1;
}

public static void main(String[] args) {
final String usage_msg = "Usage: please input the total number of people and number of people to skip.\n";

if (args.length != 2) {
System.err.print(usage_msg);
System.exit(1);
}

int n=0, k=0;
try {
n = Integer.parseInt(args[0]);
k = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.print(usage_msg);
System.exit(1);
}

if (n <= 0 || k <= 0) {
System.err.print(usage_msg);
System.exit(1);
}

int result = josephus(n, k);
System.out.println(result);
}
}