Finished naive algorithm