Let R be a Cohen-Macaulay local ring of dimension d with infinite residue field. Let I be an R-ideal that has analytic spread (I) = d, satisfies the G d condition and the weak Artin-Nagata property AN − d−2 . We provide a formula relating the length λ(I n+1 /JI n ) to the difference P I (n) −H I (n), where J is a general minimal reduction of I, P I (n) and H I (n) are respectively the generalized Hilbert-Samuel polynomial and the generalized Hilbert-Samuel function. We then use it to establish formulas to compute the generalized Hilbert coefficients of I. As an application, we extend Northcott's inequality to non-m-primary ideals. Furthermore, when equality holds, we prove that the ideal I enjoys nice properties. Indeed, if this is the case, then the reduction number of I is at most one and the associated graded ring of I is Cohen-Macaulay. We also recover results of G. Colomé-Nin, C. Polini, B. Ulrich and Y. Xie on the positivity of the generalized first Hilbert coefficient j 1 (I). Our work extends that of S. Huckaba, C. Huneke and A. Ooishi to ideals that are not necessarily m-primary.