abrar1

Josephus Problem

Feb 24th, 2022 (edited)
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3.  
  4. /*
  5. There are n people standing in a circle waiting to be executed.
  6. The counting out begins at some pouint in the circle and proceeds around the circle in a fixed direction.
  7. In each step, a certain number of people are skipped and the next person is executed.
  8. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed),
  9. until only the last person remains, who is given freedom.
  10. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and
  11. kth person is killed in circle.
  12. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.
  13.  
  14. n = 5, k = 2
  15.  
  16. 1| 2 3 4 5 ->
  17. 1 * 3| 4 5 ->
  18. 1 * 3 * 5| ->
  19. * * 3| * 5 ->
  20. * * 3 * *
  21. */
  22.  
  23.  
  24.  
  25. int josephus(int n, int k)
  26. {
  27.     if (n == 1)
  28.         return 1;
  29.     else
  30.         /* The position returned by josephus(n - 1, k) is
  31.            adjusted because the recursive call josephus(n -
  32.            1, k) considers the original position
  33.            k%n + 1 as position 1 */
  34.         return (josephus(n - 1, k) + k - 1) % n + 1;
  35. }
  36.  
  37. // Driver Program to test above function
  38. int main()
  39. {
  40.     int k = 2;
  41.     int c = 0;
  42.    
  43.     for (int i = 2; i < 4294967295 ; i+=2){    //2^32 - 1
  44.         int temp = josephus(i, k);
  45.         if( temp == i>>1 ){
  46.             printf("Number of people %d, chosen place is %d\n", i, temp);
  47.             c++;
  48.         }
  49.         if (c==10)
  50.             break;
  51.     }
  52.    
  53.     return 0;
  54. }
Add Comment
Please, Sign In to add comment