changed applyNTimes to use iterate function