Hope
Hope

Reputation: 3

Finding factors of number in C++ but I want to print number of factors on first line

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<<" ";
       }
}

Upvotes: 0

Views: 983

Answers (2)

Janaka Rajakaruna
Janaka Rajakaruna

Reputation: 19

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;
}

Upvotes: 0

jasper-bosch
jasper-bosch

Reputation: 90

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 << " ";
    }
}

Upvotes: 1

Related Questions