Supercalifragilisticexpialidocious
What is in a name?
I’m currently reading 14 books, at the same time. Well, a few pages in each book during the week. I’m glad I got all those bookmarks from my local bookstore for free.
Triangular numbers without for loop
This Programming in Objective-C 2.0 book wanted me to calculate triangular numbers with the following code:
int n, triangularNumber;
triangularNumber = 0;
for ( n - 1; n <= 200; n = n + 1)
triangularNumber += n;
Really? According to me,
T(n) = 1 + 2 + 3 + … + n
T(n+1) = 1 + 2 + 3 + … + n + (n + 1)
T(n+1) - T(n) = (n + 1) … [1]
The average value of a term in T(n) is the half the sum of the term with the biggest value and the term with the smallest value. This average term is added n times. Or:
T(n) = 0.5 * n * (n + 1) … [2]
T(n+1) = 0.5 * (n + 1) * ((n+1) + 1)
= 0.5 * (n + 1) * (n + 2)
= 0.5 * n * (n + 1) + 0.5 * 2 * (n + 1)
T(n+1) - T(n) = (n + 1) … [3]
Since [1] is the same as [3], [2] must be correct. This would give the following code to replace the earlier code:
int n, triangularNumber;
n = 200;
triangularNumber = n * (n + 1) / 2;
That seems much more efficient than using a for loop.
Reached zero tumblarity! Lower, please!
My goal is to become the least read person blogging on Tumblr, who still add posts on a regular basis. Secretly I’m hoping for sub-zero figures. Can you help me?




