
The first line contains a single integer ‘T’ denoting the number of test cases.
Each test case contains a single line with a single integer ‘N’ denoting the given number.
For each test case, print the square of the given number in a separate line.
You do not need to print anything; it has already been taken care of.
1 <= T <= 50
-10000 <= N <= 10000
Time Limit: 1 sec.
Our first intuition is to simplify multiplication into repetitive addition.
Steps are as follows:
The idea is to basically write a perfect square in terms of a series and it turns out to be the sum of the first ‘N’ odd numbers.
square(1) = 1
square(2) = 1 + 3 = 4
square(3) = 1 + 3 + 5 = 9
square(4) = 1 + 3 + 5 + 7 = 16
An edge case is when the integer is negative. We also know that the square of ‘N’ and ‘-N’ is the same, so whenever we are given a negative integer, we will convert it to a positive integer.
Our main approach here is to use bitwise operators. Let’s take a look at even and odd numbers individually.
Firstly if ‘N’ is even:
For a number to be even it needs to be a multiple of 2. So ‘N’ can be written as 2*C, where C is an integer.
Now N^2 will be (2*C)^2 = 4*C^2.
Secondly if ‘N’ is odd:
Since we know the odd number is nothing but an even number + 1. So ‘N’ can be expressed as 2*C + 1, where C is an integer.
Now N^2 will be (2*C + 1)^2 = 4*C^2 + 4*C + 1.
The steps are as follows:
In the code implementation, we’ll use the right shift operator (>>) to calculate the floor(N / 2).
An edge case is when the integer is negative. We also know that the square of ‘N’ and ‘-N’ is the same, so whenever we are given a negative integer, we will convert it to a positive integer.
Our main approach here is to use the Russian Peasant Method. It is basically used to avoid the use of a multiplication operator.
The idea is to break down the given integer in powers of two and then use the bitwise shift operators to perform the multiplication with powers of 2.
For example:
7 can be broken down into powers of 2 as 1 + 2 + 4.
7*7 can be written as 7*(1 + 2 + 4), thus to perform the multiplication we can simply use the bitwise shift operator.
The steps are as follows :