Click here to Skip to main content
15,745,506 members
Please Sign up or sign in to vote.
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:

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

1 solution

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.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900