Factor Combinations in C++

C++Server Side ProgrammingProgramming

Suppose we have a number. The numbers can be regarded as a product of its factors. So, 8 = 2 x 2 x 2; = 2 x 4. We have to make one function that takes an integer n and return all possible combinations of its factors.

So, if the input is like 12, then the output will be [[2, 6], [2, 2, 3], [3, 4]]

To solve this, we will follow these steps −

  • Define a function solve(), this will take n, target, start,

  • define one list of lists called ret

  • if n is same as 1, then −

    • return ret

  • if n is not equal to target, then −

    • insert n at the end of ret

  • for initialize i := start, when i * i <= n, update (increase i by 1), do −

    • if n mod i is same as 0, then −

      • other = solve(n / i, target, i)

      • for initialize j := 0, when j < size of other, update (increase j by 1), do −

        • insert i at the end of other[j]

        • insert other[j] at the end of ret

  • return ret

  • From the main method do the following −

  • return solve(n, n, 2)

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto< > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector < vector <int< > solve(int n, int target, int start){
      vector < vector <int< > ret;
      if(n == 1){
         return ret;
      }
      if(n != target){
         ret.push_back({n});
      }
      for(int i = start; i * i <= n; i++){
         if(n % i == 0){
            vector < vector <int< > other = solve(n / i, target,i);
            for(int j = 0; j < other.size(); j++){
               other[j].push_back(i);
               ret.push_back(other[j]);
            }
         }
      }
      return ret;
   }
   vector<vector<int<> getFactors(int n) {
      return solve(n, n, 2);
   }
};
main(){
   Solution ob;
   print_vector(ob.getFactors(16));
}

Input

16

Output

[[8, 2, ],[4, 2, 2, ],[2, 2, 2, 2, ],[4, 4, ],]
raja
Updated on 18-Nov-2020 11:33:01

Advertisements