Improved algorithm - handles large input without overflow