Given an integer, find its square without using multiplication and division operator. Also, the use of the power function from any programming language library is not allowed.

Method 1:

The idea is based on the fact that the square root of any number n can be calculated by adding odd numbers exactly n times. The relation can be expressed as:

12 = 1
22 = (1 + 3) = 4
32 = (1 + 3 + 5 = 9)
42 = (1 + 3 + 5 + 7) = 16

The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

64 16

Java


Download  Run Code

Output:

64 16

Python


Download  Run Code

Output:

64 16

Method 2: Repeatedly adding a given number to the result

The idea is to repeatedly add a given number n to the result n times. For example,

For n = 5, 52 = (5 + 5 + 5 + 5 + 5) = 25

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

64 16

Java


Download  Run Code

Output:

64 16

Python


Download  Run Code

Output:

64
16

Method 3: Using Divide and Conquer with bitwise operators

If n is even, the square of n can be expressed as n2 = ((n/2) × 2)2 = (n/2)2 × 4.

If n is odd, the square of n can be expressed as n2 = ((n - 1) + 1)2 = (n - 1)2 + 1 + 2 × (n - 1) × 1 = ((n/2)2 × 4) + 1 + (n/2) × 4.

This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

64

Java


Download  Run Code

Output:

64

Python


Download  Run Code

Output:

64 16