[Codewars] Factorial decomposition

Factorial decomposition

  • 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
27
28
29
30
31
32
33
34
35
36
37
#include <string>
using namespace std;
vector<int> prime(int n) {
vector<int> sieve(n+1);
vector<int> res;
for(int i = 2; i <= n; i++) {
if(sieve[i]) continue;
res.push_back(i);
for(int j = i * i; j <= n; j += i) sieve[j] = true;
}
return res;
}
string build(int p, int c) {
if(c == 1) return to_string(p);
return to_string(p)+"^"+to_string(c);
}
int helper(int n, int p) {
int res = 0;
for(int i = p; i <= n; i += p) {
int x = i;
while(x % p == 0) {
res += 1, x /= p;
}
}
return res;
}
std::string decomp(int n) {
vector<int> primes = prime(n);
string res = "";
for(auto p : primes) {
int cnt = helper(n,p);
res += build(p,cnt) + " * ";
}
res.pop_back();res.pop_back();res.pop_back();
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/01/PS/Codewars/factorial-decomposition/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.