1. 程式人生 > >因式分解一個正整數(遞迴方法)

因式分解一個正整數(遞迴方法)

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>

using namespace std;

void print(vector<int> const& data)
{
    cout << "{";
    for (vector<int>::const_iterator it = data.begin(); it != data.end(); ++it) {
        cout << *it << ", ";
    }
    cout << "}" << endl;
}

void combination(int n, int m, vector<int> factors)
{
    for (int i = m; i <= n; ++i) {
        vector<int> tmp = factors;
        if (n % i == 0) {
            tmp.push_back(i);
            if (n == i) {
                print(tmp);
            }
            else {
                combination(n / i, i, tmp);
            }
        }
    }
}

int factor_combination(int n)
{
    if (n <= 0) {
        return 0;
    }

    int count = 0;
    vector<int> factors;

    for (int i = 2; i <= sqrt(n); ++i) {
        if (n % i == 0) {
            factors.clear();
            factors.push_back(i);
            combination(n / i, i, factors);
        }
    }
}

int main(int argc, char** argv)
{
    int n = 0;

    if (argc != 2) {
        cout << "invalid parameters" << endl;
        return -1;
    }
    n = atoi(argv[1]);
    if (n <= 0) {
        cout << "negative parameter for n" << endl;
        return -1;
    }

    factor_combination(n);

    return 0;
}