Posted By

Scooter on 01/17/09


Tagged

math


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

wizard04


Triangular Numbers


 / 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?

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

Report this snippet  

Comments

RSS Icon Subscribe to comments
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

You need to login to post a comment.