Simplified problem6 function using reduce in both places