An alternative way to calculate squares.. without using multiplication

I was once at a party, and i was somewhat bored and i found this way of calculating the next square. It works without multiplication, so its suitable for mental calculation.

Seeing that i have recently learned python, here’s a python version of it:

n = 10 # how many sqs to return

b = []
def sq(x):
    return x*x
for y in range(1,n):
    print sq(y)
    b.append(sq(y))


def sqx(x):
    if x == 1:
        return 1
    if x == 2:
        return 4
    return (sqx(x-1)-sqx(x-2))+sqx(x-1)+2

a = []
for y in range (1,n):
    print sqx(y)
    a.append(sqx(y))

In english. First, set the first two squares to 1 and 4, since this method needs to use the two previous squares to calculate the next. Then calculate the absolute difference between these two. Suppose we are looking for 32, so previous two are 1 and 4. Abs diff is 3. Add 2 to this, result 5. Add 5 to previous square, so 4+5=9. 9 is 32.

I have no idea why this works, i just saw a pattern, and confirmed it for the first 20 integers or so.

In the code above, i have defined the function recursively. It is much slower than the other function. I suppose both are slower than the low-level premade function pow(n,m). But it certainly is cool. :P

Leave a Reply