[Codewars] Sum by Factors

Sum by Factors

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

class SumOfDivided
{
public:
static std::string sumOfDivided(std::vector<int> &lst);
};
string SumOfDivided::sumOfDivided(std::vector<int> &lst) {
map<int, long long> sum;
for(auto x : lst) {
int now = x;
if(now < 0) now = -now;
for(int i = 2; i * i <= now; i++) {
if(now % i) continue;
sum[i] += x;
while(now % i == 0) now /= i;
}
if(now != 1) sum[now] += x;
}
string res = "";
for(auto [k,v] : sum) res += "(" + to_string(k) + " " + to_string(v) + ")";
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/05/PS/Codewars/sum-by-factors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.