stochastic algorithm for the 2nd problem