-
Notifications
You must be signed in to change notification settings - Fork 0
/
SPF(Smallest Prime factors of number)
51 lines (40 loc) · 1.24 KB
/
SPF(Smallest Prime factors of number)
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
//// SPF(Smallest Prime factors of number)
//Like the smallest factors of 20 are (2,2,5) ---- 20/2=10 > 10/2=5 > 5/5=1
//APPROACH
/* > Assign Every SPF number itself like the spf of 2 is 2 and 3 is itself 3
> Check if any element is uniitilized
> check if there's already marked any number like 12 is already marked by 2 So no need to mark by 3 (Simply mark the previous 2)
> Run a loop until the remainder is not 1
> Devide the number by SPF to take LCM
*/
#include<iostream>
#include<vector>
using namespace std;
void Factor(int n){
// vector<bool> spf(n, false);
int spf[100]={0};
for(int i=2; i<=n; i++){
spf[i]=i;
}
for(int i=2; i<=n; i++){
if(spf[i]==i){
for(int j=i*i; j<=n; j+=i){
if(spf[j]==j){ //check if there's already marked any number like 12 is already marked by 2 So no need to mark by 3 (Simply mark the previous 2)
spf[j]=i;
}
}
}
}
while(n!=1){ // Run loop until the remainder is not 0;
cout<<spf[n]<<" ";
n=n/spf[n]; // update the number by SPF
}
}
int main(){
system("CLS");
int n;
cout<<"Number? :";
cin>>n;
Factor(n);
return 0;
}