Back to General discussions forum
I wrote the following code for josephus problem but it does not seem to work properly:
import java.util.*; class josephus { public static void main(String [] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(),i; int a[]=new int[n+1]; for(i=1;i<=n;i++) { a[i]=i; } int x=0,q=0; while(x<(n-1)) { for(i=1;i<=n;i++) { if(a[i]!=0) q++; if(q%k==0) {a[i]=0; x++; }}} for(i=1;i<=n;i++) { if(a[i]!=0) System.out.print(a[i]+" "); }}}
THE CODE IS:
import java.util.*;
class josephus
{
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt(),i;
int a[]=new int[n+1];
for(i=1;i<=n;i++)
{
a[i]=i;
}
int x=0,q=0;
while(x<(n-1))
{
for(i=1;i<=n;i++)
{
if(a[i]!=0)
q++;
if(q%k==0)
{a[i]=0;
x++;
}}}
for(i=1;i<=n;i++)
{
if(a[i]!=0)
System.out.print(a[i]+" ");
}}}
Never Mind. I figured out what was wrong with my solution.