Programming Puzzle Solution - April 2008

You are to write a program that finds (and prints) each series of consecutive positive integers whose sum is exactly 1,000,000. (Hint: There is more than one such series of numbers.)

// CSE Programming Puzzle - April 2008 - C++ Solution

// Print each sequence of consecutive positive integers
// whose sum is 1,000,000

#include <iostream>

using namespace std;

int main() {
  for (int i = 1; i < 199999; ++i) {
    int sum = 0;
    for (int j = i; sum < 1000000; ++j) {
      sum += j;
      if ( sum == 1000000 ) {
        cout << (j-i+1)
             << " consecutive positive integers (from "
             << i << " to " << j << ") sum to 1,000,000  ["
             << endl;
        for (int k = i; k <= j ; ++k) {
          if ( k == i ) cout << " " << k;
          else cout << "," << endl << " " << k;
          }
        cout << "  ]" << endl << endl << endl;
        i = j;
        }
      else if (sum > 1000000) break;
      }
    }
  return 0;
} // main


<?php
// CSE Programming Puzzle - April 2008 - PHP Solution

// Print each sequence of consecutive positive integers
// whose sum is 1,000,000

for ($i = 1; $i < 199999; ++$i) {
  $sum = 0;
  for ($j = $i; $sum < 1000000; ++$j) {
    $sum += $j;
    if ( $sum == 1000000 ) {
      echo ($j-$i+1) .
        " consecutive positive integers (from $i to $j)" .
        " sum to 1,000,000  [\n";
      for ($k = $i; $k <= $j ; ++$k) {
        if ( $k == $i ) echo " $k";
        else echo ",\n $k";
        }
      echo "  ]\n\n\n";
      $i = $j;
      }
    else if ($sum > 1000000) break;
    }
  }
?>

If you have solutions to this puzzle in other programming languages, please submit them to webmaster {at} cse.unt.edu and we will post them here.