Print all unique combination of factors of a given number

后端 未结 9 711
挽巷
挽巷 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:37

    vector GetAllFactors(unsigned int number)
    {
        vector factors;
    
        for (int i = 2; i <= number; i++)
        {
            if (number % i == 0)
            {
                factors.push_back(i);
            }
        }
    
        return factors;
    }
    
    void DoCombinationWithRepetitionFactors(vector allFactors, unsigned currentProduct, unsigned targetProduct, vector currentFactorSet, unsigned currentFactorIndex)
    {
        if (currentProduct == targetProduct)
        {
            for (auto a : currentFactorSet)
            {
                cout << a << " , ";
            }
    
            cout << endl;
    
            return;
        }
    
    
        for (int i = currentFactorIndex; i < allFactors.size(); i++)
        {
            if (currentProduct * allFactors[i] <= targetProduct)
            {
                currentFactorSet.push_back(allFactors[i]);
                DoCombinationWithRepetitionFactors(allFactors, currentProduct * allFactors[i], targetProduct, currentFactorSet, i);
                currentFactorSet.pop_back();
            }
        }
    }
    

提交回复
热议问题