Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 40e0474

Browse files
committed
Josephus Problem added
1 parent 76ca43d commit 40e0474

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎AlgorithmCode/JosephusProblem.java‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
System.out.println(josephus(n, k));
28+
29+
n = 5;
30+
k = 2;
31+
System.out.println(josephus(n, k));
32+
}
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /