![]() |
VOOZH | about |
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.
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.
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.
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.