-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprime_factor_decomposition.cpp
67 lines (60 loc) · 1.19 KB
/
prime_factor_decomposition.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <string>
#include <map>
#include <vector>
#include <sstream>
#include <cmath>
#include <iostream>
void primefactors(int n, std::vector<int> & factors){
while(n % 2 == 0){
factors.push_back(2);
n = n /2;
}
for(int i = 3; i <= sqrt(n); i = i+2){
while(n % i == 0){;
factors.push_back(i);
n = n / i;
}
}
if(n > 2){
factors.push_back(n);
}
}
std::map<int, int> make_map(std::vector<int> v){
std::map<int, int> m;
for(auto & e:v){
m[e] += 1;
}
return m;
}
std::string create_string(std::map<int, int> factors){
std::string join_by;
std::stringstream ss;
for(const auto p: factors){
if(ss.str() == ""){
join_by = "";
}
else
{
join_by = " * ";
}
if(p.second == 1){
ss << join_by << p.first;
}else{
ss << join_by << p.first << "^" << p.second;
}
}
return ss.str();
}
std::string decomp(int n) {
std::vector<int> factors;
for(int i = 1; i <= n; i++){
primefactors(i, factors);
}
std::map<int, int> factors_map = make_map(factors);
std::string fact_string = create_string(factors_map);
std::cout << fact_string << '\n';
return fact_string;
}
int main(){
decomp(25);
}