Elegant and fast solution for problem 18