Find square of a number without using multiplication and division operator

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

Method 1:

The idea is based on the fact that 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

C++ implementation –

Output: 64 16

Method 2: (Repeatedly adding given number to the result)

The idea is to repeatedly add given number n to the result n times. For example, for n = 5
52 = (5 + 5 + 5 + 5 + 5) = 25

C++ implementation –

Output: 64 16

Method 3: (Using Divide and Conquer with bitwise operators)

if n is even, square of n can be expressed as
n2 = (n/2)4

if n is odd, square of n can be expressed as
n2 = ((n – 1) + 1)2 = (n – 1)2 + 1 + 2 * (n – 1)*1 = (n/2)4 + 1 + (n/2)*4

C++ implementation –

Output: 64 16

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂