A solution to POJ 1785