Skip to content

Commit

Permalink
Solve 'Integers: Recreation One' kata
Browse files Browse the repository at this point in the history
  • Loading branch information
borisskert committed Jun 20, 2024
1 parent a730fc5 commit 733e6be
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
12 changes: 12 additions & 0 deletions include/integers_recreation_one/SumSquaredDivisors.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#ifndef CPP_KATAS_SUMSQUAREDDIVISORS_H
#define CPP_KATAS_SUMSQUAREDDIVISORS_H

#include <utility>
#include <vector>

class SumSquaredDivisors {
public:
static std::vector<std::pair<long long, long long>> listSquared(long long m, long long n);
};

#endif //CPP_KATAS_SUMSQUAREDDIVISORS_H
57 changes: 57 additions & 0 deletions src/integers_recreation_one/SumSquaredDivisors.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include <utility>
#include <vector>
#include <cmath>

/**
* https://www.codewars.com/kata/55aa075506463dac6600010d/train/cpp
*/
class SumSquaredDivisors {
public:
static std::vector<std::pair<long long, long long>> listSquared(long long m, long long n);
};

static std::vector<long long> divisors(long long n) {
std::vector<long long> divs;

for (long long i = 1; i * i <= n; i++) {
if (n % i == 0) {
divs.push_back(i);

if (i != n / i) {
divs.push_back(n / i);
}
}
}

return divs;
}

static long long squaredSum(const std::vector<long long> &divs) {
long long sum = 0;

for (long long div: divs) {
sum += div * div;
}

return sum;
}

static bool isSquare(long long n) {
auto root = (long long) sqrt(n);
return root * root == n;
}

std::vector<std::pair<long long, long long>> SumSquaredDivisors::listSquared(long long int m, long long int n) {
std::vector<std::pair<long long, long long>> result;

for (long long i = m; i <= n; i++) {
std::vector<long long> divs = divisors(i);
long long sum = squaredSum(divs);

if (isSquare(sum)) {
result.emplace_back(i, sum);
}
}

return result;
}
28 changes: 28 additions & 0 deletions test/integers_recreation_one/SumSquaredDivisors_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include <utility>
#include <vector>
#include <igloo/igloo_alt.h>
#include "integers_recreation_one/SumSquaredDivisors.h"

using namespace igloo;

using Result = std::vector<std::pair<long long, long long>>;

void testequal(const Result &ans, const Result &sol) {
Assert::That(ans, Equals(sol));
}

void dotest(long long m, long long n, const Result &expected) {
testequal(SumSquaredDivisors::listSquared(m, n), expected);
}

Describe(listSquared_Tests) {
It(Fixed_Tests) {
dotest(1, 250, {{1, 1},
{42, 2500},
{246, 84100}});
dotest(42, 250, {{42, 2500},
{246, 84100}});
dotest(250, 500, {{287, 84100}});
dotest(300, 600, {});
}
};

0 comments on commit 733e6be

Please sign in to comment.