My code is passing only one test case (first one) out of three. I am unable to figure out the errors because the test cases which I have tried on my own are successfully passing. Please help me either by telling me the test cases given in problem or should I share my code?
Failed test cases in "Playing with cards" problem
Please post your code as we are not allowed to provide you the system test cases.
import java.util.*;
public class Cards
{
int data[];
int top;
public static final int DEFAULT_CAPACITY=10;
public Cards() throws Exception
{
this(DEFAULT_CAPACITY);
}
public Cards(int capacity) throws Exception
{
if(capacity<1)
throw new Exception(“Invalid capacity”);
this.data=new int[capacity];
this.top=-1;
}
public int size() // O(1)
{
return(this.top+1);
}
public boolean isEmpty() // O(1)
{
return this.size()==0;
}
public void push(int value) throws Exception // O(1)
{
if(this.size()==this.data.length)
throw new Exception(“Stack is full.”);
this.top++;
this.data[this.top]=value;
}
public int pop() throws Exception // O(1)
{
if(size()==0)
throw new Exception(“Stack is empty.”);
int rv=this.data[this.top];
this.data[this.top]=0;
this.top–;
return rv;
}
public void display(Cards obj) // O(n)
{
for(int i=obj.top;i>=0;i--)
System.out.println(obj.data[i]);
}
public int nthPrime(int n)
{
int nth = n;
int num, count, i;
num=1;
count=0;
while (count < nth){
num=num+1;
for (i = 2; i <= num; i++)
{ //Here we will loop from 2 to num
if (num % i == 0)
{
break;
}
}
if ( i == num)
count = count+1;
}
return num;
}
public void iteration(int Q) throws Exception
{
Cards B[]=new Cards[Q+1];
Cards A[]=new Cards[Q+1];
A[0]=new Cards();
A[0]=this;
for(int i=1;i<=Q;i++)
{
A[i]=new Cards();
B[i]=new Cards();
while(!A[i-1].isEmpty())
{
int prime=nthPrime(i);
int temp=A[i-1].pop();
if(temp%prime==0)
{
B[i].push(temp);
}
else
{
A[i].push(temp);
}
}
}
for(int j=1;j<=Q;j++)
{
display(B[j]);
}
display(A[Q]);
}
public static void main(String[] args) throws Exception
{
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int Q=sc.nextInt();
Cards stack=new Cards(N);
for(int i=1;i<=N;i++)
{
stack.push(sc.nextInt());
}
stack.iteration(Q);
}
}
First of all, you need to optimise your code. Use a sieve to precaculate the first 10^6 primes, that should reduce the complexity of your solution.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.