forked from abbh07/DataStructure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Factors.cpp
51 lines (44 loc) · 837 Bytes
/
Factors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//Program to compute all the factors of a number
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int> factors;
//Primitive method by looping until n/2
//There are no factors of a number n greater than n/2 other than n
for(int i = 1;i<=n/2;i++)
{
if(n%i==0)
{
factors.push_back(i);
}
}
factors.push_back(n);
for(int i=0;i<factors.size();i++)
{
cout<<factors[i]<<" ";
}
cout<<endl;
factors.clear();
//Optimized method by looping until sqrt(n)
//This follows from the fact that a*b = n, where a & b are the cofactors of n
for(int i=1;i<=sqrt(n);i++)
{
if(n%i == 0)
{
factors.push_back(i);
if(i!=sqrt(n))
factors.push_back(n/i);
}
}
for(int i=0;i<factors.size();i++)
{
cout<<factors[i]<<" ";
}
cout<<endl;
return 0;
}