better iterative algorithm