- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJosephusProblem.java
More file actions
Latest commit
33 lines (27 loc) · 801 Bytes
/
Copy pathJosephusProblem.java
File metadata and controls
33 lines (27 loc) · 801 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* An implementation of the Josephus problem Time complexity: O(n)
*
* @author Micah Stairs
*/
publicclassJosephusProblem {
// Suppose there are n people in a circle and person
// 0 kill the k'th person, then the k'th person kills
// the 2k'th person and so on until only one person remains.
// The question is who lives?
// Let n be the number of people and k the hop size
publicstaticintjosephus(intn, intk) {
int[] dp = newint[n];
for (inti = 1; i < n; i++) dp[i] = (dp[i - 1] + k) % (i + 1);
returndp[n - 1];
}
publicstaticvoidmain(String[] args) {
intn = 41, k = 2;
System.out.println(josephus(n, k));
n = 25;
k = 18;
System.out.println(josephus(n, k));
n = 5;
k = 2;
System.out.println(josephus(n, k));
}
}