Created
February 16, 2019 18:47
-
-
Save Const-me/6dcbbcba77ca243115ef94ed4a2a3a3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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