recursive function for 2nd algorithm