Skip to content

Instantly share code, notes, and snippets.

@Const-me Const-me/triples.cpp
Created Feb 16, 2019

Embed
What would you like to do?
#include <iostream>
#include <array>
#include <experimental/generator>
using namespace std::experimental;
using Triple = std::array<int, 3>;
// Generate infinite sequence of Pythagorean triples
generator<Triple> triples()
{
for( int c = 2; true; c++ )
for( int b = 2; b < c; b++ )
for( int a = 2; a < b; a++ )
{
if( a * a + b * b == c * c )
co_yield Triple{ a, b, c };
}
}
// Take first `count` elements from the sequence
template<class E>
generator<E> take( generator<E> sequence, int count )
{
int i = 0;
for( auto e : sequence )
{
co_yield e;
i++;
if( i >= count )
break;
}
}
int main()
{
for( auto t : take( triples(), 100 ) )
std::cout << t[ 0 ] << ", " << t[ 1 ] << ", " << t[ 2 ] << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.