Write a program to print all the combinations of factors of given number n.
Examples:
Input : 16
Output :2 2 2 2
2 2 4
2 8
4 4
Input : 12
Output : 2 2 3
2 6
3 4
To solve this problem we take one array of array of integers or list of list of integers to store all the factors combination possible for the given n. So, to achieve this we can have one recursive function which can store the factors combination in each of its iteration. And each of those list should be stored in the final result list.
Below is the implementation of the above approach.
C++
#include <iostream>
#include <vector>
using namespace std;
void backtrack( int start, int target, vector< int >& factors,
vector<vector< int > >& combinations, int n)
{
if (target == 1) {
if (factors.size() > 1 || factors[0] != n) {
combinations.push_back(factors);
}
return ;
}
for ( int i = start; i <= target; i++) {
if (target % i == 0) {
factors.push_back(i);
backtrack(i, target / i, factors, combinations,
n);
factors.pop_back();
}
}
}
vector<vector< int > > factorCombinations( int n)
{
vector<vector< int > > combinations;
vector< int > factors;
backtrack(2, n, factors, combinations, n);
return combinations;
}
int main()
{
int n = 12;
vector<vector< int > > combinations
= factorCombinations(n);
cout << "All the combinations of factors of " << n
<< " are:" << endl;
for (vector< int > combination : combinations) {
for ( int factor : combination) {
cout << factor << " " ;
}
cout << endl;
}
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class FactorCombinations {
public static List<List<Integer> >
factorCombinations( int n)
{
List<List<Integer> > combinations
= new ArrayList<>();
backtrack( 2 , n, new ArrayList<>(), combinations, n);
return combinations;
}
private static void
backtrack( int start, int target, List<Integer> factors,
List<List<Integer> > combinations, int n)
{
if (target == 1 ) {
if (factors.size() > 1 || factors.get( 0 ) != n) {
combinations.add( new ArrayList<>(factors));
}
return ;
}
for ( int i = start; i <= target; i++) {
if (target % i == 0 ) {
factors.add(i);
backtrack(i, target / i, factors,
combinations, n);
factors.remove(factors.size() - 1 );
}
}
}
public static void main(String[] args)
{
int n = 12 ;
List<List<Integer> > combinations
= factorCombinations(n);
System.out.printf(
"All the combinations of factors of %d are:%n" ,
n);
for (List<Integer> combination : combinations) {
System.out.println(combination);
}
}
}
|
Python
def backtrack(start, target, factors, combinations, n):
if target = = 1 :
if len (factors) > 1 or factors[ 0 ] ! = n:
combinations.append( list (factors))
return
for i in range (start, target + 1 ):
if target % i = = 0 :
factors.append(i)
backtrack(i, target / / i, factors, combinations, n)
factors.pop()
def factorCombinations(n):
combinations = []
factors = []
backtrack( 2 , n, factors, combinations, n)
return combinations
if __name__ = = '__main__' :
n = 12
combinations = factorCombinations(n)
print ( "All the combinations of factors of {} are:" . format (n))
for combination in combinations:
print (combination)
|
C#
using System;
using System.Collections.Generic;
namespace FactorCombinations {
class Program {
static void Main( string [] args)
{
int n = 12;
List<List< int > > combinations
= FactorCombinations(n);
Console.WriteLine(
$
"All the combinations of factors of {n} are:" );
foreach (List< int > combination in combinations)
{
Console.WriteLine(
string .Join( " " , combination));
}
}
static List<List< int > > FactorCombinations( int n)
{
List<List< int > > combinations
= new List<List< int > >();
Backtrack(2, n, new List< int >(), combinations, n);
return combinations;
}
static void Backtrack( int start, int target,
List< int > factors,
List<List< int > > combinations,
int n)
{
if (target == 1) {
if (factors.Count > 1 || factors[0] != n) {
combinations.Add( new List< int >(factors));
}
return ;
}
for ( int i = start; i <= target; i++) {
if (target % i == 0) {
factors.Add(i);
Backtrack(i, target / i, factors,
combinations, n);
factors.RemoveAt(factors.Count - 1);
}
}
}
}
}
|
Javascript
function backtrack(start, target, factors, combinations, n) {
if (target === 1) {
if (factors.length > 1 || factors[0] !== n) {
combinations.push([...factors]);
}
return ;
}
for (let i = start; i <= target; i++) {
if (target % i === 0) {
factors.push(i);
backtrack(i, target / i, factors, combinations, n);
factors.pop();
}
}
}
function factorCombinations(n) {
const combinations = [];
const factors = [];
backtrack(2, n, factors, combinations, n);
return combinations;
}
const n = 12;
const combinations = factorCombinations(n);
console.log(`All the combinations of factors of ${n} are:`);
for (let combination of combinations) {
console.log(combination.join( ' ' ));
}
|
Output
All the combinations of factors of 12 are:
[2, 2, 3]
[2, 6]
[3, 4]
Time Complexity: O(sqrt(n) * log(n)), where n is the input integer.
Auxiliary Space: O(log(n)), where n is the input integer.
Another Approach:
The code below is pure recursive code for printing all combinations of factors:
It uses a vector of integer to store a single list of factors and a vector of integer to store all combinations of factors. Instead of using an iterative loop, it uses the same recursive function to calculate all factor combinations.
C++
#include <bits/stdc++.h>
using namespace std;
vector<vector< int > > factors_combination;
void compute_factors( int current_no, int n, int product,
vector< int > single_list)
{
if (current_no > (n / 2) || product > n)
return ;
if (product == n) {
factors_combination.push_back(single_list);
return ;
}
single_list.push_back(current_no);
compute_factors(current_no, n, product * current_no,
single_list);
single_list.pop_back();
compute_factors(current_no + 1, n, product,
single_list);
}
int main()
{
int n = 16;
vector< int > single_list;
compute_factors(2, n, 1, single_list);
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;
}
|
Java
import java.util.*;
class GFG{
static Vector<Vector<Integer>> factors_combination =
new Vector<Vector<Integer>>();
static void compute_factors( int current_no, int n, int product,
Vector<Integer> single_list)
{
if (current_no > (n / 2 ) || product > n)
return ;
if (product == n)
{
factors_combination.add(single_list);
for ( int i = 0 ; i < factors_combination.size(); i++)
{
for ( int j = 0 ; j < factors_combination.get(i).size(); j++)
System.out.print(factors_combination.get(i).get(j) + " " );
}
System.out.println();
factors_combination = new Vector<Vector<Integer>>();
return ;
}
single_list.add(current_no);
compute_factors(current_no, n,
product * current_no,
single_list);
single_list.remove(single_list.size() - 1 );
compute_factors(current_no + 1 , n, product,
single_list);
}
public static void main(String[] args)
{
int n = 16 ;
Vector<Integer> single_list = new Vector<Integer>();
compute_factors( 2 , n, 1 , single_list);
}
}
|
Python3
factors_combination = []
def compute_factors(current_no, n, product, single_list):
global factors_combination
if ((current_no > int (n / 2 )) or (product > n)):
return
if (product = = n):
factors_combination.append(single_list)
for i in range ( len (factors_combination)):
for j in range ( len (factors_combination[i])):
print (factors_combination[i][j], end = " " )
print ()
factors_combination = []
return
single_list.append(current_no)
compute_factors(current_no, n, product * current_no, single_list)
single_list.pop()
compute_factors(current_no + 1 , n, product, single_list)
n = 16
single_list = []
compute_factors( 2 , n, 1 , single_list)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static List<List< int >> factors_combination = new List<List< int >>();
static void compute_factors( int current_no, int n, int product, List< int > single_list)
{
if (current_no > (n / 2) || product > n)
return ;
if (product == n) {
factors_combination.Add(single_list);
for ( int i = 0; i < factors_combination.Count; i++)
{
for ( int j = 0; j < factors_combination[i].Count; j++)
Console.Write(factors_combination[i][j] + " " );
}
Console.WriteLine();
factors_combination = new List<List< int >>();
return ;
}
single_list.Add(current_no);
compute_factors(current_no, n, product * current_no, single_list);
single_list.RemoveAt(single_list.Count - 1);
compute_factors(current_no + 1, n, product, single_list);
}
static void Main() {
int n = 16;
List< int > single_list = new List< int >();
compute_factors(2, n, 1, single_list);
}
}
|
Javascript
<script>
let factors_combination = [];
function compute_factors(current_no, n, product, single_list)
{
if ((current_no > parseInt(n / 2, 10)) || (product > n))
return ;
if (product == n)
{
factors_combination.push(single_list);
for (let i = 0; i < factors_combination.length; i++)
{
for (let j = 0; j < factors_combination[i].length; j++)
{
document.write(factors_combination[i][j] + " " );
}
}
document.write( "</br>" );
factors_combination = [];
return ;
}
single_list.push(current_no);
compute_factors(current_no, n, product * current_no, single_list);
single_list.pop();
compute_factors(current_no + 1, n, product, single_list);
}
let n = 16;
let single_list = [];
compute_factors(2, n, 1, single_list);
</script>
|
Output
2 2 2 2
2 2 4
2 8
4 4
Time Complexity: O(n2) , n is the size of vector
Auxiliary Space: O(n2), n is the size of vector
Please suggest if someone has a better solution which is more efficient in terms of space and time.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!