/ Published in: ASP

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

<% ' 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 %>

## Comments

Subscribe to commentsYou need to login to post a comment.

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

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

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

Last attempt:

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

@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