fixed bug causing stack overflow error due to too much recursion. Replace with while loop to avoid recursion. Passes all correctness tests but still fails most memory tests and about a third of the timing tests