New algorithm for dynamical friction of ions in a magnetized electron beam