Implemented O(n^4) method