-
Notifications
You must be signed in to change notification settings - Fork 160
/
Primefactors.cpp
49 lines (37 loc) · 996 Bytes
/
Primefactors.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
/*
Print all primer factors up to a number.
Note: we only output a repeating primer factor once.
*/
/*
solution: Print 2 factor, and divide the number as much as possible. From i=3, if
i divides number, print i and divide number by i.At last, print number directly if number is still large than 2.
Note: if we get visited primer factor, we skip it.
*/
#include <iostream>
using namespace std;
void FindPrimeFactors(unsigned int num) {
int pre = 0;
while (num%2 == 0) {
if (pre != 2) cout<<"2 ";
num = num/2;
pre = 2;
}
for (unsigned int i = 3; i*i <= num; i = i+2) {
while (num%i == 0) {
if(pre != i) cout<<i<<" ";
num = num/i;
pre = i;
}
}
if (num > 2) {
if (pre != num) cout<<num<<" ";
pre = num;
}
}
int main() {
unsigned int num;
cin>>num;
cout<<"The primer factors of "<<num<<" are:"<<endl;
FindPrimeFactors(num);
return 0;
}