#include <stdio.h>
int final[3];
int checkprime(int n,int loopcount)
{
int flag=0,m;
for(m=2; m<=loopcount; m++)
{
if(n%m==0 && n!=2)
{
flag=1;
return 0;
break;
}
else if(n==2)
{
flag=0;
break;
}
}
if(flag==0)
{
return 1;
}
}
int main()
{
int test_no,n,i,j,k,m,max=1,loopcount,product=1,max_available=0,count=0;
scanf(" %d",&test_no);
for(i=0; i<3; i++)
{
scanf(" %d",&n);
int array[n];
for(j=0; j<n; j++)
{
scanf(" %d",&array[n]);
loopcount=array[n]/2;
if(max<loopcount)
{
max=loopcount;
}
}
loopcount=max;
max=array[0];
for(j=0; j<n; j++)
{
int x=checkprime(array[j],loopcount);
if(x==1)
{
if(array[j]>=max)
{
max=array[j];
}
}
}
product=product*max;
max=1;
for(j=0; j<n; j++)
{
int x=checkprime(array[j],loopcount);
if(x==1)
{
if(array[j]>max && product!=array[j])
{
max=array[j];
max_available=1;
}
else if(array[j]>=max && product==array[j] && max_available==0)
{
max=product;
}
}
if(x==0)
{
count++;
}
}
if(count==n || count==n-1)
{
final[i]=-1;
}
else
{
product=product*max;
final[i]=product;
}
product=1;
}
for(i=0; i<3; i++)
{
printf("%d\n",final[i]);
}
return 0;
}
The above code is not working properly ,I am unable to get the reason behind this , I am finding prime number two times and I have used a variable loopcount so as to find the number of iterations for checking whether the number is prime or not .
I have initially taken an array of size 3 and I am providing 3 inputs with each input of different array size and then I iterate twice for finding the maximum product , If I don't find any prime number , I output -1 on the output screen . Th first line depicts the total number of inputs which can be viewed as the number of test cases and for each test case , the first line depicts the size of array and the second line depicts the elements present in the array .Please help me to identify the problem , for the first input it is printing -1 but with some issues , Ideally , it should only go to if part
if(count==n || count==n-1)
{
final[i]=-1;
}
but it is going to code snippet of else part ,
else
{
product=product*max;
final[i]=product;
}
This I checked by writing printf statements in the else part , so I am able to get the value printed for the first input ,this is quite confusing since when if part is getting executed then why is the else part getting executed ?And for the rest inputs , it is printing garbage values .
Here is a input set:
3
5
1 4 6 8 10
3
2 2 9
2
156 13
The corresponding output is:
-1
4
169