Python Squares

by Bryan Arnold — on  ,  , 

2017-06-10-python-squares

Square Functions

Every once in a while you come across a problem where you need a function that isn't in a standard Python Egg (library/package). What to do? Well, make your own of course!

I came across this problem on CodeFights:

Given an integer $n$, return the smallest integer $a$, such that $a$ is a square of some integer and is greater than $n$.

Example:

For $n = 5$, the output should be

nextSquare(n) = 9.

In [1]:
def intSqrt(n):
    x = n
    y = (x + 1) // 2
    while y < x:
        x = y
        y = (x + n // x) // 2
    return x

via Newton's method for solving $x^2-n=0$.

Let's check it's working:

In [2]:
intSqrt(10)
Out[2]:
3
In [3]:
intSqrt(16)
Out[3]:
4

Looks good!

Now let's get an 'isSquare' function that returns a Boolean.

In [4]:
def isSquare(n):
    if intSqrt(n)**2 == n:
        return True
    return False

Examples:

In [5]:
isSquare(10)
Out[5]:
False
In [6]:
isSquare(36)
Out[6]:
True

And finally:

In [7]:
def nextSquare(n):
    return (intSqrt(n)+1)**2

Does it work?

In [8]:
nextSquare(10)
Out[8]:
16
In [9]:
nextSquare(16)
Out[9]:
25

Sure, does! :)