find the nth triangular number in php

To find the nth triangular number in PHP, we can use a loop to iterate and add up the numbers from 1 to n, which are the terms in the sequence. The formula for the nth triangular number is:

main.php
T_n = 1 + 2 + 3 + ... + n
26 chars
2 lines

We can implement this in PHP as follows:

main.php
function nth_triangular_number($n) {

  // initialize sum to 0
  $sum = 0;

  // add up the numbers from 1 to n
  for ($i = 1; $i <= $n; $i++) {
    $sum += $i;
  }

  // return the nth triangular number
  return $sum;
}
221 chars
14 lines

We can then call this function with a value of n to get the nth triangular number. For example:

main.php
// find the 10th triangular number
$triangular_10 = nth_triangular_number(10);
echo "The 10th triangular number is: " . $triangular_10; // Output: The 10th triangular number is: 55
181 chars
4 lines

Note that we could also use the formula T_n = n(n+1)/2 to find the nth triangular number directly, but the loop implementation is more general and easier to understand.

gistlibby LogSnag