Problem 1: Circular Elimination
Points:
Small Case: 10 Answer: 106
Large Case: 20 Answer: 88999997
N numbers (1 to N) are arranged in a circular fashion. Starting from kth(<N), every second number is eliminated from the circle. You need to determine the xth(<N) number which is removed.
Small Case, N=1000, x=555, k=888.
large case, N=999999999, x=55555, k=88888888.
Solution:
This problem is commonly known as Extended Josephus Problem
The Reursive formula for the case when counting starts from 1 is given by:
J(n,x) = 1, if n=1 and x=1
2, if n>1 and x=1
1, if n,z>1 and J(n-1,x-1)=n-1
J(n-1,x-1)+2, if J(n-1,x-1)<=n-2
Now, for the case when counting starts from k, we just shift kth value to 1st, and find kth number in circle.
Reference: Armin Shams-Baragh, Formulating The Extended Josephus Problem
Code:
#include <stdio.h>
long long Josephus(long long n, long long x)
{
if(n==1 && x==1)
return 1;
if(n>1 && x==1)
return 2;
long long res = Josephus(n-1,x-1);
if(res==(n-1))
return 1;
if(res <= n-2)
return res+2;
}
int main()
{
long long n,x,k,res;
scanf("%lld%lld%lld",&n,&x,&k);
res = Josephus(n,x)+k-1;
printf("%lld\n",res>n?res-n:res);
}
Submit your solution
You need to be logged in to submit a solution.
discussions
| antalg | Start number |
| Q: | If k=4, does that mean:Remove 4, skip 5, remove 6 or Skip 4, remove 5, skip 6, remove 7? |
| A: | It means Skip 4, remove 5, skip 6, remove 7? |
| anjan2 | question unclear |
| Q: | if N=10 and k=5 then what is the first eleminated number? |
| A: | If we start counting from 5, 6 is the second number, so 6 is eliminated first |
| codeprav | clarify |
| Q: | suppose 1 to 10,then for x=5,k=8.answer=2 or not? |
| A: | No. Eliminatio order is: 1st 9, 2nd 1, 3rd 3, 4th 5, 5th 7 |
| gmunkhbaatarmn | Count |
| Q: | if N=10; k=5; x=1 then answer is: 5? or 7? |
| A: | answer is 6. for numbers 1,2,3,4,5,6,7,8,9,10, if we start couting from k=5, x=1 elimination is 6 |
| akash0604 | que |
| Q: | kth term is taken as 0th term or 1st term to consider the 2nd number? |
| A: | kth term is taken as first term |
| porsh | Question Unclear |
| Q: | What is x,k? |
| A: | xth number is the number removed in xth elimination. k is the number in the circle. For example if N=10 and k=5, we start elimination with couting starting from number 5. |
post a question
Loading...



