refactored algorithm using algebra instead of brute force