========================================================== Sum3 Problem Overview ========================================================== Basic Description ================== The *Sum3* problem is described by a rather simple question: Given a set of :math:`n` integers, how many triples of distinct elements in that list add up to 0. For example, given the following list:: -1, -2, 0, 2, 3 the answer is 2:: -1 + -2 + 3 = 0 -2 + 0 + 2 = 0 The simplest way to code a solution to the *Sum3* problem is to use a double nested looping structure to generate the indices of all possible triples in the input array. Clearly, this is simple to express in code, but has an unfortunate time complexity of :math:`O(n^3)`. For example, the following C++ code uses 3 ``for`` loops to achieve a correct solution. .. highlight:: c :linenothreshold: 0 :: #include using namespace std; int main( ) { int dataSize = 5; int* data = new int[ dataSize ]; data[0] = -1; data[1] = -2; data[2] = 0; data[3] = 2; data[4] = 3; // do the naive Sum3 computation. O(n^3) int count = 0; for (int i = 0; i < dataSize-2; i++) for (int j = i+1; j < dataSize-1; j++) for (int k = j+1; k < dataSize; k++) if (data[i] + data[j] + data[k] == 0) count++; cout<< count < #include using namespace std; int getRandInt( int* dataVec, int dataSize ) { // load up a vector with random integers int num; for( int i = 0; i < dataSize; i++ ) { // integers will be 1-100 num = rand() % 100 +1; if( rand( ) % 2 == 0 ) { // make some integers negative num *= -1; } dataVec[i] = num; } } int main(int argc, char * argv[] ) { int dataSize = 0; if( argc < 2 ) { std::cerr << "usage: exe [num of nums] [optional seed value]" << std::endl; exit( -1 ); } { std::stringstream ss1; ss1 << argv[1]; ss1 >> dataSize; } if( argc >= 3 ) { std::stringstream ss1; int seed; ss1 << argv[2]; ss1 >> seed; srand( seed ); } else { srand( 0 ); } // create a data vector int* data = new int[ dataSize ]; // load it up with random data getRandInt( data, dataSize ); int *dataPtr = &data[0]; // do the naive Sum3 computation. O(n^3) int count = 0; for (int i = 0; i < dataSize-2; i++) for (int j = i+1; j < dataSize-1; j++) for (int k = j+1; k < dataSize; k++) if (dataPtr[i] + dataPtr[j] + dataPtr[k] == 0){ count++; } cout<< count <