short version of first algorithm