recursive algorithm doesn't crash, but incorrect result