Skip to content

Commit 3ee6828

Browse files
authored
Merge pull request ashutosh97#60 from sakshijha0610/master
Josephus's problem
2 parents 2a68cf7 + 2997a27 commit 3ee6828

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

Josephus's Problem/josephus.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import java.io.*;
2+
import java.util.Scanner;
3+
4+
class Josephus {
5+
6+
static int josephus(int n, int k)
7+
{
8+
if (n == 1)
9+
return 1;
10+
else
11+
return (josephus(n - 1, k) + k-1) % n + 1;
12+
}
13+
14+
public static void main(String[] args)
15+
{
16+
Scanner s = new Scnner(System.in);
17+
int n = s.nextInt();
18+
int k = s.nextInt();
19+
System.out.println("The chosen place is " + josephus(n, k));
20+
}
21+
}

Josephus's Problem/question.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.
2+
3+
Example, if n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then person at position 4 is killed, then person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives.
4+
5+
If n = 7 and k = 3, then the safe position is 4. The persons at positions 3, 6, 2, 7, 5, 1 are killed in order, and person at position 4 survives.

0 commit comments

Comments
 (0)