Integers: Recreation One
Examples:
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]Solutions
π§ C++
#include <vector>
#include <numeric>
#include <sstream>
#include <cmath>
#include <utility>
#include <string>
using ll = long long;
class SumSquaredDivisors
{
public:
static std::string listSquared(ll m, ll n)
{
std::vector<std::pair<ll,ll>> res;
for(ll i = m; i <=n; i++)
{
//find divisors
std::vector<ll> divisors;
for(ll j = 1; j<=i; ++j)
if(i%j == 0)
divisors.push_back(j);
//power all divisors
std::for_each( divisors.begin(), divisors.end(), [](ll & x){x=std::pow(x,2);});
ll sum_of_elems = std::accumulate(divisors.begin(), divisors.end(), 0);
double divisors_sqrt = std::sqrt(sum_of_elems);
if ( divisors_sqrt-(int)divisors_sqrt == 0.0)
res.push_back({i, sum_of_elems});
}
//if we found nothing
if(!res.size())
return "{}";
//format vector of pairs to string via stringstream
std::stringstream ss_resstr;
ss_resstr << "{";
for (auto k : res)
ss_resstr<<"{"<<k.first<<", " << k.second << "}, ";
std::string resstr = ss_resstr.str();
resstr.replace(resstr.end()-2, resstr.end(), "}");
return resstr;
}
};Last updated