We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 76ca43d commit 40e0474Copy full SHA for 40e0474
AlgorithmCode/JosephusProblem.java
@@ -0,0 +1,33 @@
1
+/**
2
+ * An implementation of the Josephus problem Time complexity: O(n)
3
+ *
4
+ * @author Micah Stairs
5
+ */
6
+
7
+public class JosephusProblem {
8
9
+ // Suppose there are n people in a circle and person
10
+ // 0 kill the k'th person, then the k'th person kills
11
+ // the 2k'th person and so on until only one person remains.
12
+ // The question is who lives?
13
+ // Let n be the number of people and k the hop size
14
+ public static int josephus(int n, int k) {
15
+ int[] dp = new int[n];
16
+ for (int i = 1; i < n; i++) dp[i] = (dp[i - 1] + k) % (i + 1);
17
+ return dp[n - 1];
18
+ }
19
20
+ public static void main(String[] args) {
21
22
+ int n = 41, k = 2;
23
+ System.out.println(josephus(n, k));
24
25
+ n = 25;
26
+ k = 18;
27
28
29
+ n = 5;
30
+ k = 2;
31
32
33
+}
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments