Third-order many-body perturbation theory calculations for the beryllium and magnesium isoelectronic sequences