implement smarter solution

- use apache math
- clean up naive solution