Consider the following task:
Print the first 100 squares using at most one loop. The constraints are that you are not allowed to use multiplication or functions.
To tackle this one, we will have to use one interesting property of the squares that I noticed while taking my kid to school. At the school, there was a table with all natural numbers listed from 1 to 100. While looking at it, I noticed the distances between the squares kept increasing by 2k + 1 for every kth square.
So for example, from 1 to 4 (the first square), the distance is 3. Since this is the first square, k = 1 so 2*1 + 1 = 3. The distance from 4 to 9 (the second square) is 5. Since this is the second square, k = 2 so 2*2 + 1 = 5. And so on.
Naturally I tried to generalize this and came to the following recurrent relation:
Before we use this relation in our program, we will first prove its correctness.
We will prove that by induction.
The base case is which is true. Now, we assume that
. If we add
to both sides, we get
. Thus the identity is proven.
Now, here is our simple program:
var s = 1;
for (var i = 1; i <= 100; i++) {
console.log(s);
s += i + i + 1;
}