Pex4Fun ( lets you program in C#, Visual Basic, and F# from your browser or (Windows) Phone. Created by Microsoft Research , it’s a great tool for learning about programing. Learning is done through solving puzzles, for example working out the nth Hexagonal number or the Factorial of a number. Upon solving a puzzle, you can rate it Fun, Boring, or Fishy, and you get 2 extra points (your score gets put onto the leaderboard).

One challenge however, is a bit strange.

The challenge (ChallengeGeometricSeries) asks you to work out the Geometric Series where the first value is 7, and the sum of the first two values is 21.

A geometric series is the sum of a collection of numbers that increase geometrically, i.e. by a common ratio. A geometric series is calculated by:


  • x is the number of terms to include (i.e. the first x terms)
  • Sumx is the sum of the first x terms
  • a is the first value in the series
  • r is the ratio between values

For example if we want to know the sum of the first 5 powers of two ( 2 + 4 + 8 + 16 + 32 ) (which increase by a ratio of two) it would look like this:

Coming back to Pex for fun, using the sum formula above, we therefore know that the sum of the first x values will be:

What got me thinking was that it said that the secret implementation result where x is 63 (i.e. the sum of the first 63 values of the secret sequence) is negative 7:

Not only does the sum of the first 63 values not equal to (they add up to approximately 3.23 × 1019), but it is mathematically impossible to get a negative result (the ratio, r, is bigger than 1, therefore rx will always be a positive number).

Taking this to Visual Studio to do some debugging, the reason behind the fishy answer of -7 clear. An int in C#, by default, is a signed 32-bit integer, i.e. its possible values are limited to between -(232) and 231 – 1 (between -2,147,483,648 and 2,147,483,647 ). Knowing this, it is clear why the secret implementation result is not the right answer (it is too big to store in an int data type), but why is it negative 7?

This is because in calculating the power through a loop, e.g.
static int Power(int startnumber, int power)
 int total = 1;
 for (int i = 0; i < power; i++)
  total *= startnumber;
 return total;

Once the limit of a (32-bit) integer has been reached (obviously it would be better if the Puzzle method were to be a double rather than an int), rather than giving an exception, the number (in this case total) goes to zero. When this comes back to the Puzzle method, the return value becomes -7 because

static int Puzzle(int x)
 int a = 7;
 int r = 2;
 return a * ((Power(r,x) - 1) / r - 1);


blog comments powered by Disqus