## Posted By

Scooter on 01/17/09

## Who likes this?

1 person have marked this snippet as a favorite

# Triangular Numbers

/ Published in: ASP

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?

`<%    ' 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.     ' Returns the triangular number for a given number.    function triangularNumber(someNumber)        dim i        dim result         result = 0         for i = 1 to someNumber            result = result + i        next         triangularNumber = result    end function%>`

Posted By: MarcusT on December 28, 2009

I fail to comprehend why you are using a loop at all (which will take longer and longer to compute as the number of iterations increases) when the Wikipedia page that you yourself linked to states clearly that the formula is Tn = (n * (n + 1)) / 2 and therefore allows the Nth triangular number to be found in a single calculation.

Hence: function triangularNumber(n) triangularNumber = (n * (n + 1)) / 2 end function

Posted By: MarcusT on December 28, 2009

function triangularNumber(n) triangularNumber = (n * (n + 1)) / 2 end function

Posted By: MarcusT on December 28, 2009

Damn this Markdown + lack of preview + lack of editing!

Last attempt:

``````function triangularNumber(n)
triangularNumber = (n * (n + 1)) / 2
end function
``````
Posted By: MarcusT on December 28, 2009

Great, now it's correctly formatted but the grey on black makes it illegible! I'm giving up on this site...

Posted By: wizard04 on January 5, 2010

@MarcusT Yes, Snipplr really needs to fix the Markdown. For now, take a look at a workaround here http://snipplr.com/view/22799/snipplr-workaround-code-in-comments/

Also, I made a user stylesheet for the Stylish add-on in Firefox that makes everything look a lot more legible here http://userstyles.org/styles/9213