My program gives correct output on PC. On submission of code I get ‘Time limit exceeded’ error. What might be reasons for this error how can I remove it?
following is my code for problem Prime Pattern (link:Prime Pattern)
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Scanner sc=new java.util.Scanner(System.in);
int testcase=sc.nextInt();
while((testcase--)!=0)
{
System.out.println(findNeigh(sc.nextInt(),sc.nextInt()));
}
sc.close();
}
private static int findNeigh(int xdest, int ydest) {
// TODO Auto-generated method stub
int[] distances={5,5,5,5,5,5,5,5,5};
int counter=0;
for(int i=-1;i<2 ;i++)
{
for(int j=-1;j<2;j++)
{
{
if(checkprime(findNumber(xdest+i, ydest+j)))
{
distances[counter]=Math.abs(xdest-(xdest+i)) + Math.abs(ydest-(ydest+j));
if(distances[counter]==0)
{
return 0;
}
}
counter++;
}
}
}
return getMinValue(distances);
}
public static int getMinValue(int[] array){
int minValue = array[0];
for(int i=1;i<array.length;i++){
if(array[i] < minValue){
minValue = array[i];
}
}
return minValue;
}
private static boolean checkprime(int findNumber) {
// TODO Auto-generated method stub
if(findNumber<2) return false;
for(int i=2; i<=findNumber/2; i++){
if(findNumber % i == 0){
return false;
}
}
return true;
}
private static int findNumber(int xdest, int ydest) {
// TODO Auto-generated method stub
int x=0,y=0,number=0,iter=1;
char sign='+', axis='x';
while(true)
{
switch(axis)
{
case 'x':
switch(sign)
{
case '+':
for(int i=0;i<iter;i++)
{
if(checkCondition(xdest,ydest,x,y))
{
return number;
}
number++;
x++;
}
break;
case '-':
for(int i=0;i<iter;i++)
{
if(checkCondition(xdest,ydest,x,y))
{
return number;
}
number++;
x--;
}
break;
}
axis='y';
break;
case 'y':
switch(sign)
{
case '+':
for(int i=0;i<iter;i++)
{
if(checkCondition(xdest,ydest,x,y))
{
return number;
}
number++;
y++;
}
sign='-';
break;
case '-':
for(int i=0;i<iter;i++)
{
if(checkCondition(xdest,ydest,x,y))
{
return number;
}
number++;
y--;
}
sign='+';
break;
}
axis='x';
iter++;
break;
}
}
}
private static boolean checkCondition(int xdest, int ydest, int x, int y) {
// TODO Auto-generated method stub
if(x==xdest && y==ydest)
{
return true;
}
return false;
}
}