finally got a working solution that doesn't take 10^6 years to calculate via brute force