Efficient calculation of the energy of a molecule in an arbitrary electric field