Skip to content

Commit ac5f46e

Browse files
authored
Add Josephus Problem in C (#4348)
1 parent 7b077b7 commit ac5f46e

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

archive/c/c/josephus-problem.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int josephus(int n, int k) {
5+
if (n == 1)
6+
return 1;
7+
else
8+
return (josephus(n - 1, k) + k - 1) % n + 1;
9+
}
10+
11+
int main(int argc, char *argv[]) {
12+
if (argc != 3) {
13+
printf("Usage: please input the total number of people and number of people to skip.\n");
14+
return 1;
15+
}
16+
17+
char *endptr;
18+
int n = strtol(argv[1], &endptr, 10);
19+
if (*endptr != '\0' || n <= 0) {
20+
printf("Usage: please input the total number of people and number of people to skip.\n");
21+
return 1;
22+
}
23+
24+
int k = strtol(argv[2], &endptr, 10);
25+
if (*endptr != '\0' || k <= 0) {
26+
printf("Usage: please input the total number of people and number of people to skip.\n");
27+
return 1;
28+
}
29+
30+
int result = josephus(n, k);
31+
printf("%d\n", result);
32+
33+
return 0;
34+
}

0 commit comments

Comments
 (0)