Posted By

Scooter on 01/17/09


Tagged

math


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

wizard04
umang_nine


Triangular Numbers


 / Published in: PHP
 

URL: http://reusablecode.blogspot.com/2009/01/triangular-numbers.html

Before some troll comes along and criticizes this function, bear in mind that it has legitimate uses. For example, it can be used to solve the handshake problem: how many handshakes if each person in a room full of n+1 total people shakes hands once with each other person?

  1. <?php
  2. /*
  3.   Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved.
  4.  
  5.   This work is licensed under the Creative Commons Attribution License. To view
  6.   a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or
  7.   send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
  8.   94305, USA.
  9.   */
  10.  
  11. function triangularNumber($number)
  12. {
  13. for($i = 1; $i <= $number; $i++)
  14. {
  15. $result += $i;
  16. }
  17.  
  18. return $result;
  19. }
  20. ?>

Report this snippet  

You need to login to post a comment.