Calculate square of a number

Posted: 28 Jan, 2021
Difficulty: Easy


Try Problem

Given an integer ‘N’, you are supposed to return the square of the given integer without using multiplication (*), division (/) or power function (pow()).

Input format:
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.
Output format:
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.
Approach 1

Our first intuition is to simplify multiplication into repetitive addition.

Steps are as follows:


  • Square of ‘N’ means N*N.
  • This can also be written as the addition of ‘N’ to the result ‘N’ times.
  • For example Square(3) = 3 + 3 + 3 = 9.
  • So we will run a loop ‘N’ times and keep on adding ‘N’ to the result in each iteration.
  • 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.
Try Problem