rorschack

Factors

Mar 26th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <math.h>
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. //Find factors of a number
  8.  
  9. using namespace std;
  10.  
  11. int main(int argc, char *argv[]) {
  12.     int n;
  13.     vector<int> vec;
  14.     if(argc==1) {
  15.         cout << "Enter a positive decimal number: ";
  16.         cin >> n;
  17.     } else n=atoi(argv[1]);
  18.     cout << "Factors of " << n << " are:\n";
  19.     for(int i=1;i<=sqrt(n);i++) { //Reduce time complexity of O(n) to O(sqrt(n))
  20.          //when a*b=n then a and b both are the factors
  21.         if(n%i==0) {
  22.             vec.push_back(i);
  23.             if(i!=sqrt(n)) //do not include b if a=b
  24.                 vec.push_back(n/i);
  25.         }
  26.     }
  27.     sort(vec.begin(),vec.end());//sort the vector
  28.     vector<int>::iterator v=vec.begin();
  29.     while(v!=vec.end()) {
  30.         cout << *v << endl;
  31.         v++;
  32.     }
  33.     return 0;
  34. }
Add Comment
Please, Sign In to add comment