now uses a bit better algorithm than brute force