implemented another better algorithm