I try to solve Sum by Factors on CodeWars and I have no idea how to get it working with C++. My code prints just the highest prime factor for every number. Good solution is: I = {12, 15}; // result = "(2 12)(3 27)(5 15)"
and mine is Expected: equal to (2 12)(3 27)(5 15)
Actual: (3 12)(3 27)(5 15)
. Can anybody take a look at this code and help me find correct solution?
I don't want to rewrite for instance Python code to Cpp, just trying to improve myself.
#include <string>
#include <vector>
#include <utility>
#include <cmath>
#include <numeric>
class SumOfDivided
{
public:
static std::string sumOfDivided(std::vector<int> &lst)
{
std::vector<std::pair<int, int>> v;
std::string rtn = "";
int sum = std::accumulate(lst.begin(), lst.end(), 0);
v.emplace_back(std::make_pair(primeFactors(std::ref(sum)), std::ref(sum)));
for(auto& elem : lst)
v.emplace_back(std::make_pair(primeFactors(std::ref(elem)), std::ref(elem)));
sort(v.begin(), v.end());
for(auto& elem : v)
rtn += "(" + std::to_string(elem.first) + " " + std::to_string(elem.second) + ")";
return rtn;
}
static int primeFactors(int& n)
{
int helper = 2;
int number = abs(n);
while(number > helper)
if(number % helper == 0)
{
number /= helper;
helper = 2;
}
else
helper++;
return helper;
}
};
Aucun commentaire:
Enregistrer un commentaire