Print all unique combination of factors of a given number

后端 未结 9 762
挽巷
挽巷 2021-02-08 05:46

What is the most efficient algorithm to print all unique combinations of factors of a positive integer. For example if the given number is 24 then the output should be

9条回答
  •  面向向阳花
    2021-02-08 06:43

    I have a solution without recursion or sorting or stacks in C/C++.

    #include 
    #include 
    
    // For each n, for each i = n-1 to 2, try prod = prod*i, if prod < N.
    
    int
    g(int N, int n, int k)
    {
            int i = k;
            int prod = n;
            std::vector myvec;
    
            myvec.push_back(n);
            while (i > 1) {
                    if (prod * i == N) {
                            prod = prod*i;
                            myvec.push_back(i);
                            for (auto it = myvec.begin();
                                    it != myvec.end(); it++) {
                                    std::cout << *it << ",";
                            }
                            std::cout << std::endl;
                            return i;
                    } else if (prod * i < N) {
                            prod = prod*i;
                            myvec.push_back(i);
                    } else { i--;}
            }
    
            return k;
    }
    
    void
    f(int N)
    {
            for (int i = 2; i <= N/2; i++) {
                    int x = g(N, i, i-1);
                    // Extract all possible factors from this point
                    while (x > 0) {
                            x = g(N, i, x-1);
                    }
            }
    }
    
    int
    main()
    {
            f(24);
    
            return 0;
    }
    

    And output is like this:

    $ ./a.out
        3,2,2,2,
        4,3,2,
        6,4,
        6,2,2,
        8,3,
        12,2,
    

提交回复
热议问题