Friday, December 5, 2014

print factors

printFactors(int n)

input:32
  output:
    1 * 32
    2 * 16
    2 * 2 * 8
    2 * 2 * 2 * 4
    2 * 2 * 2 * 2 * 2
    2 * 4 * 4
    4 * 8


Answer:
  vector<vector<int> > printFactors(int n) {
    vector<vector<int> > results;
    vector<int> result;
    recur(n, 2, results, result);
    return results;
}
void recur(int n, int start, vector<vector<int> > &results, vector<int> &result)
{
    if (n == 1) {
        results.push_back(result);
        return;
    }
    for (int i = start; i <= n; ++i) {
        if (n%i == 0) {
            result.push_back(i);
            recur(n/i, i, results, result);
            result.pop_back();
        }
    }
}

No comments:

Post a Comment