solution using an iterrative algorithm