Derivation of Lüscher's finite size formula for Nπ and NN system