Last active
January 4, 2016 19:49
-
-
Save Jangwa/8670187 to your computer and use it in GitHub Desktop.
Question - There are n persons numbered from 0 to n - 1 standing in a circle. The person number K, counting from the person number 0, is executed. After that the person number k of the remaining persons is executed, counting from the person after the last executed one. The process continues until only one person is left. This person is a survivo…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Iterative version | |
int jos(int K,int N) | |
{ | |
int r =0; | |
for(int i=1;i<=N;i++) | |
{ | |
r = r + K%i; | |
} | |
return r; | |
} | |
Recursive version | |
int josephus(int n, int k) | |
{ | |
if (n == 1) | |
return 1; | |
else | |
/* The position returned by josephus(n - 1, k) is adjusted because the | |
recursive call josephus(n - 1, k) considers the original position | |
k%n + 1 as position 1 */ | |
return (josephus(n - 1, k) + k-1) % n + 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment