...

/

Solution Review: Compute the Square of a Number

Solution Review: Compute the Square of a Number

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

Solution #1: Multiplying Number with Itself

Press + to interact
function findSquare(testVariable) {
return testVariable * testVariable;
}
// Driver Code
var testVariable = 5;
console.log(findSquare(testVariable));

Explanation

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

Solution #2: Recursive Method

Press + to interact
function findSquare(testVariable) {
// Base case
if (testVariable == 0) {
return 0;
}
// Recursive case
else {
return findSquare(testVariable - 1) + (2 * testVariable) - 1;
}
}
// Driver Code
var testVariable = 5;
console.log(findSquare(testVariable));

Explanation

Let’s break the problem down mathematically. We’ll 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 ...