Sum of cardinal integers

A fellow developer was discussing his football pool. The players select a winner for each of the 16 NFL games. Each game is ranked. You get points based on the ranking. The question of the maximum number of points came up.

The maximum points would be:
16 + 15 + 14 + 13 + 12 + 11 + 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1

This is 136. I remembered that with even numbers, you could calculate this value with the formula i / 2 * (i + 1). This is because 16 + 1 = 15 + 2 = 14 + 3, etc.

For odd numbers, you use the even number calculation and add the odd number to the result.

I then wondered if I could calculate any arbitrary positive integer with a single statement. I came up with the follwing after a couple minutes:

(i + 1 – i Mod 2) * Int(i / 2) + i * (i Mod 2)

This appears to work until we overflow the data type. A stupid example, but it provided me a little diversion from the humdrum.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: