Calculate square of a number

Easy
0/40
Average time to solve is 15m
profile
Contributed by
68 upvotes
Asked in company
Salesforce

Problem statement

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

Detailed explanation ( Input/output format, Notes, Images )
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.
Note:
You do not need to print anything; it has already been taken care of.
Constraints:
1 <= T <= 50
-10000 <= N <= 10000

Time Limit: 1 sec.
Sample Input 1:
2
3
-4
Sample Output 1:
9
16
Explanation to Sample Input 1:
In the first test case, the square of 3 is 9.

In the second test case, the square of -4 is 16. 
Sample Input 2:
2
-13
1
Sample Output 2:
169
1
Hint

Think of simplifying multiplication into repetitive addition.

Approaches (4)
Addition

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.
Time Complexity

O(N), where ‘N’ is the given integer.

 

Since we are going through ‘N’ iterations so the overall time complexity will be O(N).

Space Complexity

O(1)

 

Since no extra space is required, the overall space complexity will be O(1).

Code Solution
(100% EXP penalty)
Calculate square of a number
Full screen
Console