Modified algorithm to make it more time-efficient, correct results for large-1.in