Skip to content

Commit 3c645f3

Browse files
authored
Add Josephus Problem in Go (#4501)
1 parent ae3fa46 commit 3c645f3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

archive/g/go/josephus-problem.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package main
2+
3+
import (
4+
"os"
5+
"strconv"
6+
)
7+
8+
func die() {
9+
println("Usage: please input the total number of people and number of people to skip.")
10+
os.Exit(1)
11+
}
12+
13+
func josephus(n, k int) int {
14+
if n == 1 {
15+
return 1
16+
}
17+
18+
return (josephus(n-1, k)+k-1)%n + 1
19+
}
20+
21+
func main() {
22+
if len(os.Args) != 3 {
23+
die()
24+
}
25+
26+
n, err := strconv.Atoi(os.Args[1])
27+
if err != nil {
28+
die()
29+
}
30+
31+
k, err := strconv.Atoi(os.Args[2])
32+
if err != nil {
33+
die()
34+
}
35+
36+
println(josephus(n, k))
37+
}

0 commit comments

Comments
 (0)