Solution Review: Compute the Square of a Number
This review provides a detailed analysis of the way to compute the square of an input number.
We'll cover the following...
Solution #1: Iterative Method:
Press + to interact
def findSquare(testVariable) :return testVariable * testVariable# Driver CodetestVariable = 5print(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 caseif targetNumber == 0 :return 0# Recursive caseelse :return findSquare(targetNumber - 1) + (2 * targetNumber) - 1# Driver CodetargetNumber = 5print(findSquare(targetNumber))
Explanation
Let’s break the problem down mathematically. We will compute the square of a number through direct recursion:
To implement the square operation as a recursive function, we first need to express the square operation in terms of itself:
Mathematically we know the following:
...