15,745,506 members
1.00/5 (1 vote)
See more:
you can see the josephus problem at Josephus problem - Wikipedia[^] and i already know the solution that doesn't use recursion but i really want to know how this one works. in this case i'm using the step 2 which means when it deletes n(a number) then it jumps n+1 and then deletes n+2.

What I have tried:

C++
```<pre>
#include <stdio.h>
#include <stdlib.h>
int winner(int n){
if (n==1)
return 1;
else
return (winner(n-1)+1)%n+1;
}
int main()
{
int n;
scanf("%d", &n);
printf("%d", winner(n));
return 0;
}```
Posted
Updated 17-Nov-18 5:58am
v2

## Solution 1

What's to explain? Either you understand recursion, or you need to learn it.
To learn recursion is simple to do: just learn recursion.

The winner method is called with a specific value for n. If it isn't one (i.e. the winning position) it calls itself with n minus one, and uses the result from that to calculate teh winning position.
If you understand how recursion works, it's pretty clear.

So grab the debugger, and follow the code through. It's worth making a quick change first. Change this:
`return (winner(n-1)+1)%n+1;`

to this:
```{
int res = winner(n-1);
res = res + 1;
res = res % n + 1;
return res;
}```
That way, you can follow exactly what is being done (and returned) at each stage.