14,040,432 members
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:

```<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.

Top Experts
Last 24hrsThis month
 OriginalGriff 205 Patrice T 100 Gerry Schmitz 50 Richard MacCutchan 50 CHill60 40
 OriginalGriff 3,679 Maciej Los 1,464 Dave Kreskowiak 1,345 Patrice T 1,258 Gerry Schmitz 1,177

Web02 | 2.8.190425.1 | Last Updated 17 Nov 2018