Skip to content

Instantly share code, notes, and snippets.

@Const-me
Created February 16, 2019 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Const-me/6dcbbcba77ca243115ef94ed4a2a3a3a to your computer and use it in GitHub Desktop.
Save Const-me/6dcbbcba77ca243115ef94ed4a2a3a3a to your computer and use it in GitHub Desktop.
#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