Practical numbers: Difference between revisions
m
C++ performance improvement
(Added C++ solution) |
m (C++ performance improvement) |
||
Line 72:
#include <vector>
// Returns true if any subset of
template <typename iterator>
bool sum_of_any_subset(int n,
if (
return false;
if (std::find(
return true;
int total = std::accumulate(
if (n == total)
return true;
if (n > total)
return false;
return
}
Line 106 ⟶ 107:
std::vector<int> f = factors(n);
for (int i = 1; i < n; ++i) {
if (!sum_of_any_subset(i, f.begin(), f.end()))
return false;
}
Line 136 ⟶ 137:
std::cout << "Found " << practical.size() << " practical numbers:\n"
<< shorten(practical, 10) << '\n';
for (int n : {666, 6666, 66666, 672, 720, 222222})▼
std::cout << n << " is " << (is_practical(n) ? "" : "not ")
▲ for (int n : {666, 6666, 66666, 672, 720})
return 0;
}</lang>
Line 144 ⟶ 145:
{{out}}
<pre>
Found 77 practical numbers:▼
1, 2, 4, 6, 8, 12, 16, 18, 20, 24, ..., 288, 294, 300, 304, 306, 308, 312, 320, 324, 330
6666 is a practical number.
66666 is not a practical number.
672 is a practical number.
720 is a practical number.
222222 is a practical number.
</pre>
|