function Fidelity_LQNC = Calculate_fidelity_LQNC_N_hop_M_pair(F_in,N,M)

%QNC still calculate for M=2
number_of_pairs_QNC =3*2 + (2*N)/2;
order_QNC=zeros(1,number_of_pairs_QNC+1);% the order of fidelity, says order(4)=2, meaning 2*F^3, order ranging from 0-->7
for i =1:pow2(number_of_pairs_QNC);
    value = de2bi(i-1,number_of_pairs_QNC,'left-msb');
    termAF=power(-1,value(1))*power(-1,value(2));
    termBE=power(-1,value(3))*power(-1,value(4));
    for j=5:number_of_pairs_QNC
        termAF=termAF*power(-1,value(j));
        termBE=termBE*power(-1,value(j));
    end
    termcommon= power(-1,value(1))*power(-1,value(2))*power(-1,value(3))*power(-1,value(4));
    if ((termAF+termBE+termcommon)==3)
        temp=number_of_pairs_QNC;% for calculating the order of particular NO error pattern
        for j=1:number_of_pairs_QNC
             temp = temp - value(j);
        end
        order_QNC(temp+1)=order_QNC(temp+1)+1; % add up
    end
end
F_QNC =0;
for i =1:length(order_QNC)
    F_QNC= F_QNC + order_QNC(i)*F_in.^(i-1).*(1-F_in).^(number_of_pairs_QNC+1-i);
end
F_QNC_in=F_QNC;
F_QNC_out=F_QNC;% in case M=2
index = log2(M);
while index > 1 % > 0 for QNC
    F_QNC_out = F_QNC_in.*F_QNC_in;
    F_QNC_in = F_QNC_out;
    index=index - 1;
end
Fidelity_LQNC=F_QNC_out;