fork(7) download
  1. /*
  2.  * Lazy generation of Pythagorean Triples
  3.  * Inspired by http://b...content-available-to-author-only...i.com/2014/04/21/getting-lazy-with-c/
  4.  * John Zwinck, 2014-04-22
  5.  *
  6.  * This demonstrates a different, perhaps more C++ish solution to lazily
  7.  * generate a sequence. This approach does no dynamic memory allocation.
  8.  * The main idea is to implement a custom forward iterator (STL compatible).
  9.  *
  10.  * Separation of concerns are handled thusly:
  11.  * 1. Generating Pythagorean Triples is done by our triple_iterator.
  12.  * 2. Printing is handled by std::ostream_iterator<>.
  13.  * 3. Limiting the number of triples generated is via std::copy_n().
  14.  *
  15.  * As in the original version, the algorithm is naive.
  16.  */
  17.  
  18. #include <algorithm>
  19. #include <iostream>
  20. #include <iterator>
  21.  
  22. using namespace std;
  23.  
  24. struct triple
  25. {
  26. int x = 0;
  27. int y = 0;
  28. int z = 0;
  29. };
  30.  
  31. ostream& operator<<(ostream& out, const triple& value)
  32. {
  33. return out << value.x << ", " << value.y << ", " << value.z;
  34. }
  35.  
  36. // unbounded forward iterator producing Pythagorean Triples on demand
  37. class triple_iterator : public iterator<forward_iterator_tag, triple>, triple
  38. {
  39. public:
  40. triple_iterator() { ++*this; } // initialize to the first valid triple
  41. const triple& operator*() { return *this; }
  42.  
  43. // set ourselves to the next Pythagorean Triple
  44. triple_iterator& operator++()
  45. {
  46. // we must skip certain actions the first time through,
  47. // to give the appearance of resuming where we returned the last time
  48. bool resume = true;
  49.  
  50. for (; ; ++z) {
  51. if (!resume) {
  52. x = 1;
  53. }
  54. for (; x <= z; ++x) {
  55. if (!resume) {
  56. y = x;
  57. }
  58. for (; y <= z; ++y) {
  59. if (resume) {
  60. ++y;
  61. }
  62. if (x*x + y*y == z*z) {
  63. return *this;
  64. }
  65. resume = false;
  66. }
  67. }
  68. }
  69. }
  70. };
  71.  
  72. int main()
  73. {
  74. // write the first few Pythagorean Triples to stdout
  75. copy_n(triple_iterator(), 10, ostream_iterator<triple>(cout, "\n"));
  76. }
  77.  
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
3, 4, 5
6, 8, 10
5, 12, 13
9, 12, 15
8, 15, 17
12, 16, 20
7, 24, 25
15, 20, 25
10, 24, 26
20, 21, 29