Josephus problem solving

How does the process work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
 
int josephus(int n, int k)
{
  if (n == 1)
    return 1;
  else
 
    return (josephus(n - 1, k) + k-1) % n + 1;
}
int main()
{
  int n = 14;
  int k = 2;
  printf("The chosen place is %d", josephus(n, k));
  return 0;
}
Last edited on
You can trace it manually. You do know that the main() calls josephus(14, 2).

On that first function call the n is not 1. Therefore, the function computes and returns:
(josephus(13, 2) + 1) % 14 + 1

In order to evaluate that expression you obviously have to resolve the call: josephus(13, 2)

That is also a call of josephus(), but with different parameters. If you follow the calls deeper, you probably reach a call: josephus(1, 2) that returns 1, because n==1 on that call.
Topic archived. No new replies allowed.