0

I am able to find the factors but not getting how to print the count of factors like in Sample output in c++

Question : You are given a number N and find all the distinct factors of N

Input: First-line will contain the number N.

Output: In the first line print number of distinct factors of N. In the second line print all distinct factors in ascending order separated by space.

Constraints 1≤N≤10^6

Sample Input 1:

4

Sample Output 1:

3 //Number of factor

1 2 4 //factors

  //My code
  #include<bits/stdc++.h>
  using namespace std;
  int main(){
   int n;
   cin>>n;
   int count =0;
   for(int i=1;i<=n;i++){
    if(n%i == 0){
        count++;
        cout<<count<<endl;
        cout<<i<<" ";
       }
}
Hope
  • 3
  • 1
  • Off-topic: About [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) and even worse: [including bits/stdc++.h](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)... – Aconcagua Oct 12 '21 at 11:05
  • store the factors and only print them when you know how many they are – 463035818_is_not_an_ai Oct 12 '21 at 11:05
  • You would print the count *after* having counted the factors in the loop! – Aconcagua Oct 12 '21 at 11:06
  • In the end you have two options: 1. Run once over the loop to count the factors, print the number, then run once more to print the factors themselves. 2. Store all the factors in a `std::vector`, then print out vector's size followed by all members. – Aconcagua Oct 12 '21 at 11:09
  • Side note: you can get two factors at once: Count up up as long as `i*i <= n`, you get the second factor apart from `i` by `n/i`. – Aconcagua Oct 12 '21 at 11:12

2 Answers2

1

Store the factors in a vector:

#include <iostream>
#include <vector>

int main() {
    int n;
    std::cout << "Please enter a number" << std::endl;
    std::cin >> n;
    
    std::vector<int> factors;
    for(int i = 1; i <= n; ++i) {
        if(n%i == 0) {
            factors.push_back(i);
        }
    }
    
    std::cout << factors.size() << std::endl;
    for (std::vector<int>::iterator itr = factors.begin(); itr != factors.end(); ++itr) {
        std::cout << *itr << " ";
    }
}
  • Note that this has a complexity O(n). You can get a complexity O(sqrt(n)) by using the trick proposed in a comment by @Aconcagua – Damien Oct 12 '21 at 12:57
0

Please try following code

int main(){
int n;
cout<<"Enter Number (between 1 and 100,000,00) : ";
cin>>n;
cout<<"Factors\n-------\n";
int count =0;
for(int i=1;i<=n;i++)
{
if(n%i == 0)
{ cout<<i<<" ";
count++;
}
}cout<<"\nNumber of Factors : "<<count<<endl;
return 0;
}