fix overflow bug
replace recursion with loop