Little Elephant and Divisors | CodeChef

Getting wrong answer with code

 #include<iostream>
 #include<algorithm>
 int gcd(int a,int b)
 {
     if(b==0)
        return a;
     else
        return gcd(b,a%b);
 }
 using namespace std;
 int main()
 {
     int t;
     cin>>t;
     while(t--)
     {
         int n,p,h,flag=0;
         cin>>n;
         int a[n];
         for(int i=0;i<n;i++)
            cin>>a[i];
         p=a[0];
         for(int i=1;i<n;i++)
         {
             p=gcd(a[i],p);
             if(p==1) 
             flag=1;
             
         }
         
                
         if (flag==0)
         {
            for(int i=2;i*i<=p;i++) 
            { 
                if(p%i==0)
                {
                    p=i;
                    break;
                }
            }
         }
         else
            p=-1;
          cout<<p<<endl;
     }
     
 }

But if I put the condition

if(p==1) 
             flag=1;

out of the for loop, it works.
Can someone find out the bug?