Solution Review: Compute Square of a Number

This review provides a detailed analysis of the ways to compute the square of a number.

Solution #1: Iterative Method:

Press + to interact
def findSquare(testVariable) :
return testVariable * testVariable
# Driver Code
testVariable = 5
print(findSquare(testVariable))

Explanation

The iterative solution to this problem is simple. We multiply the input variable with itself and return the result.

Solution #2: Recursive Method:

Press + to interact
def findSquare(targetNumber) :
# Base case
if targetNumber == 0 :
return 0
# Recursive case
else :
return findSquare(targetNumber - 1) + (2 * targetNumber) - 1
# Driver Code
targetNumber = 5
print(findSquare(targetNumber))

Explanation

Let’s break the problem down mathematically. We will compute the square of a number by direct recursion:

To implement the square operation as a recursive function, we need to first express the square operation in terms of itself:

Mathematically we know that:

(n1)2=n22n+1(n-1)^2 = n^2 - 2n + 1

Let’s isolate n2n^2 to one side of the equation and rest of the components to the other side:

n2=(n1)2+2n1n^2 = (n-1)^2 + 2n - 1

This equation will be our recursive case while the squaresquare of 00 will be the base case:

if targetNumber == 0 :
    return 0

The visualization below will help you better understand this code:


How about another coding challenge?