Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <math.h>
- #include <vector>
- #include <algorithm>
- //Find factors of a number
- using namespace std;
- int main(int argc, char *argv[]) {
- int n;
- vector<int> vec;
- if(argc==1) {
- cout << "Enter a positive decimal number: ";
- cin >> n;
- } else n=atoi(argv[1]);
- cout << "Factors of " << n << " are:\n";
- for(int i=1;i<=sqrt(n);i++) { //Reduce time complexity of O(n) to O(sqrt(n))
- //when a*b=n then a and b both are the factors
- if(n%i==0) {
- vec.push_back(i);
- if(i!=sqrt(n)) //do not include b if a=b
- vec.push_back(n/i);
- }
- }
- sort(vec.begin(),vec.end());//sort the vector
- vector<int>::iterator v=vec.begin();
- while(v!=vec.end()) {
- cout << *v << endl;
- v++;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment