Print all combinations of factors (Ways to factorize)
Last Updated :
13 Aug, 2024
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;
// Function to find all factor combinations of a number
void backtrack(int start, int target, vector<int>& factors,
vector<vector<int> >& combinations, int n)
{
// Base case: if target is 1, we have found a
// factorization
if (target == 1) {
// Add a copy of the factors vector to combinations,
// except if the vector contains only one factor
// equal to n
if (factors.size() > 1 || factors[0] != n) {
combinations.push_back(factors);
}
return;
}
// Try all factors from start to target, inclusive
for (int i = start; i <= target; i++) {
if (target % i == 0) {
factors.push_back(i); // Add i to factors
backtrack(i, target / i, factors, combinations,
n); // Recursively find factors of
// target / i
factors.pop_back(); // Remove i from factors
}
}
}
// Function to call backtrack and return the factor
// combinations
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) {
// add a copy of the factors list to
// combinations, except if the list contains
// only one factor equal to n
if (factors.size() > 1 || factors.get(0) != n) {
combinations.add(new ArrayList<>(factors));
}
return;
}
// try all factors from start to target, inclusive
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):
# Base case: if target is 1, we have found a factorization
if target == 1:
# Add a copy of the factors list to combinations, except if the list contains only one factor equal to n
if len(factors) > 1 or factors[0] != n:
combinations.append(list(factors))
return
# Try all factors from start to target, inclusive
for i in range(start, target + 1):
if target % i == 0:
factors.append(i) # Add i to factors
# Recursively find factors of target // i
backtrack(i, target // i, factors, combinations, n)
factors.pop() # Remove i from factors
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) {
// add a copy of the factors list to
// combinations, except if the list contains
// only one factor equal to n
if (factors.Count > 1 || factors[0] != n) {
combinations.Add(new List<int>(factors));
}
return;
}
// try all factors from start to target, inclusive
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 to find all factor combinations of a number
function backtrack(start, target, factors, combinations, n) {
// Base case: if target is 1, we have found a factorization
if (target === 1) {
// Add a copy of the factors array to combinations, except if the array contains only one factor equal to n
if (factors.length > 1 || factors[0] !== n) {
combinations.push([...factors]);
}
return;
}
// Try all factors from start to target, inclusive
for (let i = start; i <= target; i++) {
if (target % i === 0) {
factors.push(i); // Add i to factors
backtrack(i, target / i, factors, combinations, n); // Recursively find factors of target / i
factors.pop(); // Remove i from factors
}
}
}
// Function to call backtrack and return the factor combinations
function factorCombinations(n) {
const combinations = [];
const factors = [];
backtrack(2, n, factors, combinations, n);
return combinations;
}
// Main code
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(' '));
}
OutputAll 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++
// C++ program to print all factors combination
#include <bits/stdc++.h>
using namespace std;
// vector of vector for storing
// list of factor combinations
vector<vector<int> > factors_combination;
// recursive function
void compute_factors(int current_no, int n, int product,
vector<int> single_list)
{
// base case: if the product
// 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<int> 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
Java
// Java program to print all factors combination
import java.util.*;
class GFG{
// vector of vector for storing
// list of factor combinations
static Vector<Vector<Integer>> factors_combination =
new Vector<Vector<Integer>>();
// Recursive function
static void compute_factors(int current_no, int n, int product,
Vector<Integer> single_list)
{
// base case: if the product
// 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.add(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.get(i).size(); j++)
System.out.print(factors_combination.get(i).get(j) + " ");
}
System.out.println();
factors_combination = new Vector<Vector<Integer>>();
// Into factors_combination
return;
}
// Including current_no in our list
single_list.add(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.remove(single_list.size() - 1);
// Trying to get required n
// without including current
// current_no
compute_factors(current_no + 1, n, product,
single_list);
}
// Driver code
public static void main(String[] args)
{
int n = 16;
// Vector to store single list of factors
// eg. 2,2,2,2 is one of the list for n=16
Vector<Integer> single_list = new Vector<Integer>();
// compute_factors ( starting_no, given_n,
// our_current_product, vector )
compute_factors(2, n, 1, single_list);
}
}
// This code is contributed by decode2207
Python
# Python3 program to print all factors combination
# vector of vector for storing
# list of factor combinations
factors_combination = []
# recursive function
def compute_factors(current_no, n, product, single_list):
global factors_combination
# base case: if the product
# exceeds our given number;
# OR
# current_no exceeds half the given n
if ((current_no > int(n / 2)) or (product > n)):
return
# if current list of factors
# is contributing to n
if (product == n):
# storing the list
factors_combination.append(single_list)
# printing all possible factors stored in
# factors_combination
for i in range(len(factors_combination)):
for j in range(len(factors_combination[i])):
print(factors_combination[i][j], end=" ")
print()
factors_combination = []
# into factors_combination
return
# including current_no in our list
single_list.append(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()
# trying to get required n
# without including current
# current_no
compute_factors(current_no + 1, n, product, single_list)
n = 16
# vector to store single list of factors
# eg. 2,2,2,2 is one of the list for n=16
single_list = []
# compute_factors ( starting_no, given_n,
# our_current_product, vector )
compute_factors(2, n, 1, single_list)
# This code is contributed by ukasp.
C#
// C# program to print all factors combination
using System;
using System.Collections.Generic;
class GFG {
// vector of vector for storing
// list of factor combinations
static List<List<int>> factors_combination = new List<List<int>>();
// recursive function
static void compute_factors(int current_no, int n, int product, List<int> single_list)
{
// base case: if the product
// 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.Add(single_list);
// printing all possible factors stored in
// factors_combination
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>>();
// into factors_combination
return;
}
// including current_no in our list
single_list.Add(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.RemoveAt(single_list.Count - 1);
// trying to get required n
// without including current
// current_no
compute_factors(current_no + 1, n, product, single_list);
}
static void Main() {
int n = 16;
// vector to store single list of factors
// eg. 2,2,2,2 is one of the list for n=16
List<int> single_list = new List<int>();
// compute_factors ( starting_no, given_n,
// our_current_product, vector )
compute_factors(2, n, 1, single_list);
}
}
// This code is contributed by divyesh072019.
JavaScript
<script>
// Javascript program to print all factors combination
// vector of vector for storing
// list of factor combinations
let factors_combination = [];
// recursive function
function compute_factors(current_no, n, product, single_list)
{
// base case: if the product
// exceeds our given number;
// OR
// current_no exceeds half the given n
if ((current_no > parseInt(n / 2, 10)) || (product > n))
return;
// if current list of factors
// is contributing to n
if (product == n)
{
// storing the list
factors_combination.push(single_list);
// printing all possible factors stored in
// factors_combination
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 = [];
// into factors_combination
return;
}
// including current_no in our list
single_list.push(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();
// trying to get required n
// without including current
// current_no
compute_factors(current_no + 1, n, product, single_list);
}
let n = 16;
// vector to store single list of factors
// eg. 2,2,2,2 is one of the list for n=16
let single_list = [];
// compute_factors ( starting_no, given_n,
// our_current_product, vector )
compute_factors(2, n, 1, single_list);
// This code is contributed by suresh07.
</script>
Output2 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem