where D is the density matrix obtained using the MO coefficients in the .molden file and S is the overlap matrix read from the nwchem output. However, the above expression does not evaluate to the number of electrons. I'm getting 3.71 electrons against 4.