Did Problem 1 in perl in an efficient manner