JOSEPHUS PROBLEM HELP

Back to General discussions forum

Mandeep_Verma     2016-02-19 12:08:16
User avatar

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]+" "); }}}

Mandeep_Verma     2016-02-19 12:09:29
User avatar

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]+" ");
}}}

Mandeep_Verma     2016-02-19 12:41:11
User avatar

Never Mind. I figured out what was wrong with my solution.

Please login and solve 5 problems to be able to post at forum