changed recursive method which is exponential to an iterative method