#include <map>
std::map<int, int> prime_factors(int n) {
auto factors = std::map<int, int>{};
while (n % 2 == 0) {
factors[2]++;
n = n / 2;
}
for (auto p = 3; p * p <= n; p += 2) {
while (n % p == 0) {
factors[p]++;
n = n / p;
}
}
if (n > 1) {
factors[n]++;
n = n / 1;
}
return factors;
}
// TODO: Replace examples and use TDD by writing your own tests
#include <map>
Describe(TEST)
{
It(should_do_something)
{
Assert::That(prime_factors(2), Equals(std::map<int,int>{{2, 1}}));
Assert::That(prime_factors(5), Equals(std::map<int,int>{{5, 1}}));
Assert::That(prime_factors(7), Equals(std::map<int,int>{{7, 1}}));
Assert::That(prime_factors(11), Equals(std::map<int,int>{{11, 1}}));
Assert::That(prime_factors(10), Equals(std::map<int,int>{{2, 1},{5, 1}}));
Assert::That(prime_factors(100), Equals(std::map<int,int>{{2, 2},{5, 2}}));
Assert::That(prime_factors(500), Equals(std::map<int,int>{{2, 2},{5, 3}}));
Assert::That(prime_factors(789), Equals(std::map<int,int>{{3, 1},{263, 1}}));
}
};
#include <vector>
std::vector<int> prime_factors(int n) {
auto factors = std::vector<int>{};
if (n == 0) { return factors; }
while (n % 2 == 0) {
factors.push_back(2);
n = n / 2;
}
for (auto p = 3; p * p <= n ; p += 2) {
while (n % p == 0) {
factors.push_back(p);
n = n / p;
}
}
if (n > 2) {
factors.push_back(n);
}
return factors;
}
// TODO: Replace examples and use TDD by writing your own tests
#include <vector>
Describe(Test)
{
It(should_do_something)
{
Assert::That(prime_factors(0), Equals(std::vector<int>{}));
Assert::That(prime_factors(10), Equals(std::vector{2, 5}));
Assert::That(prime_factors(20), Equals(std::vector{2, 2, 5}));
Assert::That(prime_factors(50), Equals(std::vector{2, 5, 5}));
Assert::That(prime_factors(100), Equals(std::vector{2, 2, 5, 5}));
Assert::That(prime_factors(500), Equals(std::vector{2, 2, 5, 5, 5}));
Assert::That(prime_factors(13), Equals(std::vector{13}));
Assert::That(prime_factors(17), Equals(std::vector{17}));
Assert::That(prime_factors(25), Equals(std::vector{5, 5}));
Assert::That(prime_factors(31), Equals(std::vector{31}));
Assert::That(prime_factors(81), Equals(std::vector{3, 3, 3, 3,}));
}
};
Fundamentals
Strings
#include <string> #include <fmt/ranges.h> auto digest(const std::string& param) { if (param.empty()) return param; // Oh... should check there !! return fmt::format("{}", fmt::join(param, " ")); }
- #include <string>
#include <numeric>- #include <fmt/ranges.h>
- auto digest(const std::string& param) {
- if (param.empty()) return param; // Oh... should check there !!
return std::accumulate(std::next(param.cbegin()),param.cend(),std::string(1,param[0]), // Char initializer[](auto &s, auto c) {return s+std::string{{' ',c}}; // initializer_list string initializer});- return fmt::format("{}", fmt::join(param, " "));
- }