[Codewars] Primes in numbers

Primes in numbers

  • Time :
  • Space :
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
#include <bits/stdc++.h>
using namespace std;

class PrimeDecomp
{
public:
static std::string factors(int lst);
};
string PrimeDecomp::factors(int lst) {
string res = "";
auto work = [](int p, int c) {
if(c == 1) return "(" + to_string(p) + ")";
return "(" + to_string(p) + "**" + to_string(c) + ")";
};
for(int i = 2; i * i <= lst; i++) {
if(lst % i) continue;
int count = 0;
while(lst % i == 0) {
count += 1;
lst /= i;
}
res += work(i,count);
}
if(lst != 1) res += work(lst,1);
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/05/PS/Codewars/primes-in-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.