# Help regarding a DSA LEARNING SERIES PROBLEM

i am having this problem CodeChef: Practical coding for everyone i have written the code for counting the total number of factors but i am unable to print the factors…please help by providing a solution in c++.
here is my code for counting the total number of factors in c++
#include<bits/stdc++.h>
#include <string.h>
#define ll long long int
using namespace std;
int main()
{
ll n;
cin>>n;
ll fact=0;
ll i;
for( i=1;i<=n;i++)
{
if(n%i==0)
{
fact++;
}

    }
cout<<fact<<endl;

return 0;


}

I am presuming that you are a beginner. First please put the above code by formatting it properly, ( Here’s the link) .

Now even though your logic is correct, you are not storing the factors anywhere hence you won’t be able to print them.
You need to use another data structure to store those factors. An array, a vector or something like that.

Note: You above logic has O(n) time complexity, there is a faster way to do this in
O( \sqrt n)

1 Like

You Can Understand From My Answer: CodeChef: Practical coding for everyone

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scin = new Scanner(System.in);
long n = scin.nextLong();
long half_n = Math.round(n/2);
int count = 0;
String x = "";
for (long i=1;i<=half_n;i++){
if(n%i==0){
count++;
x+=i+" ";
}
}
System.out.println(count+1);
System.out.println(x+n);
}
}



Code Is In Java