Improved recursive implementation