Heronian triangles: Difference between revisions
→{{header|C++}}: C++11 to C++17 (basically just using std::gcd)
(add RPL) |
(→{{header|C++}}: C++11 to C++17 (basically just using std::gcd)) |
||
Line 1,185:
=={{header|C++}}==
{{Works with|C++
<syntaxhighlight lang="cpp">#include <
#include <
#include <iostream>
#include <
▲#include <vector>
#include <cmath>
struct Triangle {▼
int a{};▼
int c{};▼
[[nodiscard]] constexpr auto perimeter() const noexcept { return a + b + c; }
[[nodiscard]] constexpr auto area() const noexcept {
return std::sqrt(area_sq);▼
}
▲struct Triangle
▲ int a;
▲ int c;
};
▲ double p_2 = perimeter(t) / 2.;
▲ double area_sq = p_2 * ( p_2 - t.a ) * ( p_2 - t.b ) * ( p_2 - t.c );
▲ return sqrt(area_sq);
std::vector<Triangle> result;
for(int a = 1; a <= side_limit; ++a)
for(int b = 1; b <= a; ++b)
for(int c = a + 1 - b; c <= b; ++c) // skip too-small values of c, which will violate triangle inequality
{
Triangle t{ a, b, c };
if (t_area == 0) continue;
if
result.push_back(t);
}
Line 1,241 ⟶ 1,224:
}
bool compare(const Triangle& lhs, const Triangle& rhs) noexcept {
▲ std::make_tuple(area(rhs), perimeter(rhs), std::max(rhs.a, std::max(rhs.b, rhs.c)));
}
struct area_compare {
[[nodiscard]] constexpr bool operator()(
[[nodiscard]] constexpr bool operator()(int i, const Triangle& t
▲ bool operator()(int i, const Triangle& t) { return i < area(t); }
};
int main() {
auto tri = generate_triangles();
std::cout << "There are " << tri.size() << " primitive Heronian triangles with sides up to 200\n\n";
Line 1,262 ⟶ 1,242:
std::cout << "area\tperimeter\tsides\n";
for(int i = 0; i < 10; ++i)
std::cout <<
tri[i].a << 'x' << tri[i].b << 'x' << tri[i].c << '\n';
Line 1,269 ⟶ 1,249:
std::cout << "area\tperimeter\tsides\n";
for(auto it = range.first; it != range.second; ++it)
std::cout <<
it->a << 'x' << it->b << 'x' << it->c << '\n';
}</syntaxhighlight>
|