/ 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?
Expand |
Embed | Plain Text
<?php /* Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved. This work is licensed under the Creative Commons Attribution License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. */ function triangularNumber($number) { for($i = 1; $i <= $number; $i++) { $result += $i; } return $result; } ?>
Comments
Subscribe to comments
You need to login to post a comment.

There is a mathematical trick that allows you to -dramatically- speed up the calculation, especially with regard to working with larger triangular numbers.
You can read about the method here: http://www.curiousmath.com/index.php?name=News&file=article&sid=95
Below is a proof demonstrating the difference in speed of these methods:
Whoops, my code got cut...
"; print "Triangular number 32, method 2 - ".triangularNumber_2(32)." ";
"; $start = time(); for($x = 0; $x < 1000000; $x++) { triangularNumber_2(256); } print "A million passes of 256, method 2 - ".(time() - $start)." seconds ";
Eugh, I give up with the comments on this site, you get the idea...