Exact Algorithm for Dynamics of Charged Particles in a Magnetic Field