## Posted By

Scooter on 01/17/09

## Who likes this?

2 people have marked this snippet as a favorite

# Triangular Numbers

/ Published in: PHP

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?

`<?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;    }?>`

Posted By: Omnikron13 on April 8, 2013

There is a mathematical trick that allows you to -dramatically- speed up the calculation, especially with regard to working with larger triangular numbers.

Below is a proof demonstrating the difference in speed of these methods:

Posted By: Omnikron13 on April 8, 2013

Whoops, my code got cut...

Posted By: Omnikron13 on April 8, 2013
``````<?php

function triangularNumber_1(\$_x) {
for(\$i = 1; \$i <= \$_x; \$i++) {
\$result += \$i;
}
return \$result;
}

/*
*  Due to being a simple piece of mathematics, my triangular number function is likely
*  exempt from copyright, but just in case I eschew all copyright and give it entirely
*  to the public domain.
*      --Joey Sabey
*/
function triangularNumber_2(\$_x) {
return ((\$_x / 2) + 0.5) * \$_x;
}

print "Triangular number 32, method 1 - ".triangularNumber_1(32)."
``````

"; print "Triangular number 32, method 2 - ".triangularNumber_2(32)." ";

``````\$start = time();
for(\$x = 0; \$x < 1000000; \$x++) {
triangularNumber_1(256);
}
print "A million passes of 256, method 1 - ".(time() - \$start)." seconds
``````

"; \$start = time(); for(\$x = 0; \$x < 1000000; \$x++) { triangularNumber_2(256); } print "A million passes of 256, method 2 - ".(time() - \$start)." seconds ";

``````?>
``````
Posted By: Omnikron13 on April 8, 2013

Eugh, I give up with the comments on this site, you get the idea...