Click here to Skip to main content
14,040,432 members
Rate this:
Please Sign up or sign in to 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

Rate this: bad
Please Sign up or sign in to vote.

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web02 | 2.8.190425.1 | Last Updated 17 Nov 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100