Refactored logic for nth functions