Algorithm fixed(changed 'if' for 'while')