# Segmentation fault

``````#include <bits/stdc++.h>
using namespace std;

void fact(int factors[],int result[],int n,int index,int i,int nof){

if(n==1){
for(int b=0;b<index;b++){
cout<<result[b]<<" ";
}
cout<<endl;
return;
}

for(int a=i;a<nof;a++){
if(n%factors[i]==0)
{
result[index]=factors[a];
fact(factors,result,n/factors[a],index+1,a,nof);
}
}
}

int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int factors[n];
int result[n];
int nof=0;
for(int i=1;i<=n/2;i++)
if(n%i==0)
{
factors[nof]=i;
nof++;
}
factors[nof]=n;
/*for(int i=0;i<nof;i++)
cout<<factors[i];*/
fact(factors,result,n,0,0,nof);
}
return 0;
}

The question was to print all the combinations to factorize the number.
Example
Input
1
8

Output
1 2 2 2
1 2 4
1 8``````

Reformatted (difficult to read). I’ll just leave it here -

``````#include <bits/stdc++.h>
using namespace std;

void fact(int factors[],int result[],int n,int index,int i,int nof){
if (n == 1)
{
for(int b = 0; b < index; b++)
{
cout << result[b] << " ";

}

cout << endl;
return;
}

for (int a = i; a < nof; a++) {

if (n % factors[i] == 0)
{
result[index] = factors[a];
fact(factors, result, n / factors[a], index+1, a, nof);
}
}
}

int main()
{
int t;
cin >> t;
while (t--) {
int n;
cin >> n;

int factors[n];
int result[n];
int nof = 0;

for (int i = 1; i <= n / 2; i++)

if(n % i == 0)
{
factors[nof] = i;
nof++;
}
factors[nof] = n;
fact(factors, result, n, 0, 0, nof);
}
return 0;
}

``````

Also, why `t` is not used after the loop and what is the purpose of decrementing it in a loop?

t is the no of the test case and normally it is decremented in the while loop,right?

Try this version of your code. Print statements are my favorite debugging tool.

``````#include <bits/stdc++.h>
using namespace std;

void fact(int factors[], int result[], int n, int index, int i, int nof) {
cout << "   ---- Running fact(): n = " << std::to_string(n) << ", i = " << std::to_string(i) << ", nof = " << std::to_string(nof) << endl;
if (n == 1) {
for (int b = 0; b < index; b++) {
cout << result[b] << " ";
}
cout << endl;
return;
}

for (int a = i; a < nof; a++) {
if (n % factors[i] == 0) {
result[index] = factors[a];
cout << "  --- Calling function fact() from fact()" << endl;
fact(factors, result, n / factors[a], index+1, a, nof);
}
}
}

int main() {
int t;
cout << "- Input number of test cases:" << endl;
cin >> t;
while (t--) {
cout << " -- Test case " + std::to_string(t) << endl;
cout << " -- Input test number:" << endl;
int n;
cin >> n;

int factors[n];
int result[n];
int nof = 0;

for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
cout << "  --- Logging factor " << std::to_string(i) << endl;
factors[nof] = i;
nof++;
}
}
factors[nof] = n;
cout << "  --- Calling function fact() from main()" << endl;
fact(factors, result, n, 0, 0, nof);
}
return 0;
}
``````

I like including print statements as bread crumbs. You can always comment out the debugging prints in your “production” version of your code.