📜  打印因子的所有组合(分解的方式)

📅  最后修改于: 2021-05-04 12:14:22             🧑  作者: Mango

编写程序以打印给定数字n的所有因子组合。
例子:

Input : 16
Output :2 2 2 2 
        2 2 4 
        2 8 
        4 4 

Input : 12
Output : 2 2 3
         2 6
         3 4

为了解决这个问题,我们采用整数数组或整数列表的一个数组来存储给定n可能的所有因子组合。因此,要实现这一目标,我们可以使用一个递归函数,该函数可以在每次迭代中存储因子组合。每个列表都应存储在最终结果列表中。
下面是上述方法的实现。

C++
// C++ program to print all factors combination
#include 
#include
using namespace std;
 
// defining vector of vector for
// storing factor combinations
vector>resultant;
 
// current_factor is current factor to be considered.
// current_product is current product of factors.    
void factorsListFunc (int first, int each_prod, int n,
                        vectorsingle_result_list)
{
    // base case of this recursive function
    if (first> n || each_prod > n)
        return;
 
    // When current_product is equal to n,
    // then current contain list of factors
    // so it will be added to the vect
    if (each_prod == n)
    {
        resultant.push_back(single_result_list);
        return;
    }
 
    // In this loop we first calculate factors
    // of n and then it's combination so that
    // we get the value n in a recursive way .
    for (int i = first; i < n; i++)
    {
        if (i * each_prod > n)
            break;
 
        // if i divides n
        // properly then it
        // is factor of n
        if (n % i == 0)
        {
 
            // it is added to 'single_result_list' list
            single_result_list.push_back(i);
             
            // Here function is called recursively
            // and when (i*each_prod) is equal to n
            // we will store the 'single_result_list'
            // (it is basically the list containing all
            // combination of factors) into result_list.
            factorsListFunc(i, i * each_prod, n,
                            single_result_list);
 
            // here we will empty the 'single_result_list'
            // List so that new combination of factors
            // get stored in it.
            single_result_list.pop_back();
        }
    }
}
 
// Returns a list containing all ways
// to factorize a number n.
void factComb(int n)
{
    // making list of lists to store all
    // possible combinations of factors
    vectorsingle_result_list;
     
    // function to calculate all the combinations
    // of factors
    factorsListFunc(2, 1, n, single_result_list);
}
 
// Driver Code
int main()
{
    int n = 16;
     
    // calling function for computing
    // vector of vector
    factComb(n);
 
    // printing all possible combination
    // of factors stored in vect
    for (int i = 0; i < resultant.size(); i++)
    {
        for (int j = 0; j < resultant[i].size(); j++)
            cout << resultant[i][j] << " ";
        cout << endl;
    }
    return 0;
}
 
// This code is contributed by
// Atul kumar Shrivastava


Java
// Java program to print all factors combination
import java.io.*;
import java.util.*;
class FactorsCombination {
 
    // Returns a list containing all ways to factorize
    // a number n.
    public static List > factComb(int n)
    {
        // making list of lists to store all
        // possible combinations of factors
        List > result_list =
                     new ArrayList >();
        List list = new ArrayList();
 
        // function to calculate all the combinations
        // of factors
        factorsListFunc(2, 1, n, result_list, list);
        return result_list;
    }
 
    // First is current factor to be considered.
    // each_product is current product of factors.   
    public static void factorsListFunc(int first,
                             int each_prod, int n,
    List > result_list, List       
                               single_result_list)
    {
        // Terminating condition of this recursive
        // function
        if (first > n || each_prod > n)
            return;
 
        // When each_prod is equal to n, we get
        // the list of factors in 'single_result_
        // _list' so it is  added to the result_
        // _list list .
        if (each_prod == n) {
 
            ArrayList t =
          new ArrayList(single_result_list);
 
            result_list.add(t);
 
            return;
        }
 
        // In this loop we first calculate factors
        // of n and then it's combination so that
        // we get the value n in a recursive way .
        for (int i = first; i < n; i++) {
            if (i * each_prod > n)
                break;
 
            // if i divides n
            // properly then it
            // is factor of n
            if (n % i == 0) {
 
                // it is added to 'single_result_list' list
                single_result_list.add(i);
 
                // Here function is called recursively
                // and when (i*each_prod) is equal to n
                // we will store the 'single_result_list' (it is
                // basically the list containing all
                // combination of factors) into result_list.
                factorsListFunc(i, i * each_prod, n,
                  result_list, single_result_list);
 
                // here we will empty the 'single_result_list'
                // List so that new combination of factors
                // get stored in it.
                single_result_list.remove(single_result_list.size() - 1);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 16;
        List > resultant = factComb(n);
 
        // printing all possible combination
        // of factors stored in resultant list
        for (List i : resultant) {
            for (int j : i)
                System.out.print(j + " ");           
            System.out.println();
        }
    }
}


Python3
# Python3 program to print all factors combination
 
# current_factor is current factor to be considered.
# current_product is current product of factors.    
def factorsListFunc (first, each_prod, n, single_result_list):
     
    # base case of this recursive function
    if (first> n or each_prod > n):
        return
 
    # When current_product is equal to n,
    # then current contain list of factors
    # so it will be added to the vect
    if (each_prod == n) :
        print(*single_result_list)
        return
             
    # In this loop we first calculate factors
    # of n and then it's combination so that
    # we get the value n in a recursive way .
    for i in range(first, n):
        if (i * each_prod > n):
            break
 
        # if i divides n properly, then it
        # is factor of n
        if (n % i == 0):
             
            # it is added to 'single_result_list' list
            single_result_list.append(i)
             
            # Here function is called recursively
            # and when (i*each_prod) is equal to n
            # we will store the 'single_result_list' (it is
            # basically the list containing all
            # combination of factors) into result_list.
            factorsListFunc(i, i * each_prod, n,
                             single_result_list)
             
            # here we will empty the 'single_result_list'
            # List so that new combination of factors
            # get stored in it.
            single_result_list.remove(single_result_list[-1])
 
# Returns a list containing all ways
# to factorize a number n.        
def factComb(n):
     
    # making list of lists to store all
    # possible combinations of factors
    single_result_list = []
     
    # function to calculate all the combinations
    # of factors
    factorsListFunc(2, 1, n,single_result_list)
                     
# Driver Code
n = 16
 
# calling function for computing
# vector of vector
factComb(n)
 
# This code is contributed by
# Atul kumar Shrivastava


C#
// C# program to print all factors combination
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Returns a list containing all ways
    // to factorize a number n.
    public static List > factComb(int n)
    {
        // making list of lists to store all
        // possible combinations of factors
        List > result_list =
                     new List >();
        List list = new List();
 
        // function to calculate
        // all the combinations of factors
        factorsListFunc(2, 1, n, result_list, list);
        return result_list;
    }
 
    // First is current factor to be considered.
    // each_product is current product of factors.
    public static void factorsListFunc(int first,
                            int each_prod, int n,
                    List > result_list,
                    List single_result_list)
    {
        // Terminating condition of 
        // this recursive function
        if (first > n || each_prod > n)
            return;
 
        // When each_prod is equal to n, we get
        // the list of factors in 'single_result_
        // _list' so it is added to the result_
        // _list list .
        if (each_prod == n)
        {
            List t =
                new List(single_result_list);
 
            result_list.Add(t);
 
            return;
        }
 
        // In this loop we first calculate factors
        // of n and then it's combination so that
        // we get the value n in a recursive way .
        for (int i = first; i < n; i++)
        {
            if (i * each_prod > n)
                break;
 
            // if i divides n
            // properly then it
            // is factor of n
            if (n % i == 0)
            {
 
                // it is added to 'single_result_list' list
                single_result_list.Add(i);
 
                // Here function is called recursively
                // and when (i*each_prod) is equal to n
                // we will store the 'single_result_list' (it is
                // basically the list containing all
                // combination of factors) into result_list.
                factorsListFunc(i, i * each_prod, n,
                                        result_list,
                                single_result_list);
 
                // here we will empty the 'single_result_list'
                // List so that new combination of factors
                // get stored in it.
                single_result_list.RemoveAt(single_result_list.Count - 1);
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int n = 16;
        List > resultant = factComb(n);
 
        // printing all possible combination
        // of factors stored in resultant list
        foreach (List i in resultant)
        {
            foreach (int j in i)
                Console.Write(j + " ");        
            Console.WriteLine();
        }
    }
}
 
// This code is contributed by PrinciRaj1992


C++
// C++ program to print all factors combination
#include 
using namespace std;
 
// vector of vector for storing
// list of factor combinations
vector > factors_combination;
 
// recursive function
void compute_factors(int current_no, int n, int product,
                     vector single_list)
{
     
    // base case: if the pruduct
    // exceeds our given number;
    // OR
    // current_no exceeds half the given n
    if (current_no > (n / 2) || product > n)
        return;
 
    // if current list of factors
    // is contributing to n
    if (product == n) {
       
        // storing the list
        factors_combination.push_back(single_list);
       
        // into factors_combination
        return;
    }
 
    // including current_no in our list
    single_list.push_back(current_no);
 
    // trying to get required
    // n with including current
    // current_no
    compute_factors(current_no, n, product * current_no,
                    single_list);
 
    // excluding current_no from our list
    single_list.pop_back();
 
    // trying to get required n
    // without including current
    // current_no
    compute_factors(current_no + 1, n, product,
                    single_list);
}
 
// Driver Code
int main()
{
    int n = 16;
 
    // vector to store single list of factors
    // eg. 2,2,2,2 is one of the list for n=16
    vector single_list;
 
    // compute_factors ( starting_no, given_n,
    // our_current_product, vector )
    compute_factors(2, n, 1, single_list);
 
    // printing all possible factors stored in
    // factors_combination
    for (int i = 0; i < factors_combination.size(); i++) {
        for (int j = 0; j < factors_combination[i].size();
             j++)
            cout << factors_combination[i][j] << " ";
        cout << endl;
    }
    return 0;
}
 
// code contributed by Devendra Kolhe


输出
2 2 2 2 
2 2 4 
2 8 
4 4 

另一种方法:

下面的代码是纯递归代码,用于打印因子的所有组合:

它使用整数向量存储单个因子列表,并使用整数向量存储所有因子组合。它没有使用迭代循环,而是使用相同的递归函数来计算所有因子组合。

C++

// C++ program to print all factors combination
#include 
using namespace std;
 
// vector of vector for storing
// list of factor combinations
vector > factors_combination;
 
// recursive function
void compute_factors(int current_no, int n, int product,
                     vector single_list)
{
     
    // base case: if the pruduct
    // exceeds our given number;
    // OR
    // current_no exceeds half the given n
    if (current_no > (n / 2) || product > n)
        return;
 
    // if current list of factors
    // is contributing to n
    if (product == n) {
       
        // storing the list
        factors_combination.push_back(single_list);
       
        // into factors_combination
        return;
    }
 
    // including current_no in our list
    single_list.push_back(current_no);
 
    // trying to get required
    // n with including current
    // current_no
    compute_factors(current_no, n, product * current_no,
                    single_list);
 
    // excluding current_no from our list
    single_list.pop_back();
 
    // trying to get required n
    // without including current
    // current_no
    compute_factors(current_no + 1, n, product,
                    single_list);
}
 
// Driver Code
int main()
{
    int n = 16;
 
    // vector to store single list of factors
    // eg. 2,2,2,2 is one of the list for n=16
    vector single_list;
 
    // compute_factors ( starting_no, given_n,
    // our_current_product, vector )
    compute_factors(2, n, 1, single_list);
 
    // printing all possible factors stored in
    // factors_combination
    for (int i = 0; i < factors_combination.size(); i++) {
        for (int j = 0; j < factors_combination[i].size();
             j++)
            cout << factors_combination[i][j] << " ";
        cout << endl;
    }
    return 0;
}
 
// code contributed by Devendra Kolhe
输出
2 2 2 2 
2 2 4 
2 8 
4 4