Wrong answer in MAXAND18

#include <iostream>
using namespace std;
unsigned int countSetBits(int n)
    {
        unsigned int count = 0;
        while (n) {
            n &= (n - 1);
            count++;
        }
        return count;
    }
    int fun(unsigned int n)
{
    return n & (n - 1);
}
int main()
{
    long int t;
    cin>>t;
    while(t--)
    {
        long long int n,i;
        cin>>n;
        long long int a[n];
        long long int k;
        cin>>k;

        for(i=0;i<n;i++)
        {
            cin>>a[i];

        }
        long long int p=a[0];
        for(i=1;i<n;i++)
        {
            p=(p|a[i]);
        }
        long long int bits = countSetBits(p);
        long long int val=bits-k ;
        if(val<0)
        {
            val=val*(-1);
            while(val--)
            {
                p=p<<1;
                p=p+1;
            }
        }
        else
        while(val--)
        {
           p=fun(p);
        }
        long long int sum=0;
        for(i=0;i<n;i++)
        {

            sum=sum+(p&a[i]);
        }
        cout<<p<<endl;

    }



    return 0; }

is my logic wrong and why ?