Implementation of first naive method (O(n^6))