Robson » Little Red Book » Triangular numbers

Chapter 3 - Question 8

The numbers 1, 3, 6, 10 are called triangular.


                     .
. . .
. . . . . .
. . . . . . . . . .
1 3 6 10

Write a program to generate all the triangular numbers less than 1000.

Solution 1

<?
   // start the sequence at 1
   $numbers[] = 1;
   // loop if last generated triangular number is less than 1000
   while (array_sum($numbers) < 1000)
   {
       // add the sum of all numbers in the array to the triangular sequence
       $triangular[] = array_sum($numbers);
       // add the last number plus one,
       // so the array will look like this after six loops:
       // 1, 2, 3, 4, 5, 6
       $numbers[] = $numbers[count($numbers)-1]+1;        
   }
   // output the sequence
   echo implode(', ', $triangular);
?>

Which produces:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990

Log

© 2004-17 robson | cc unless stated