Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding square of a number

I found this question,

write a function that returns a square of given integer n without using multiplication.

Solution to this is

public static int sq(int n){
        int i = n;
        int sq = 0;
        int count = 0;

        while(i > 0){
            if((i & 1) == 1){
                sq += n << count;
            }

            i = i >> 1;
            count++;
        }

        return sq;
    }

I understand what the function is doing, but I don't understand why this is working.

Can anyone explain why this is a working solution?

like image 426
user3189106 Avatar asked Feb 18 '15 07:02

user3189106


People also ask

Is there a trick to squaring numbers?

Step 1: Add the last digit of the number you are trying to square to the entire number itself, creating your sum. Step 2: Multiply the sum (step 1) by the first digit of the base number. Step 3: Square the last digit of the base number.


1 Answers

Because multiplication distributes over addition. This probably sounds mysterious, but that really is the reason. Consider this multiplication:

100 * 111

Obviously that just 111 shifted left by two: 11100

This code is doing that for every bit that is 1 in i, and summing the results. So it turns for example 111 * 111 into

001 * 111 = 00111
010 * 111 = 01110
100 * 111 = 11100
            -----  +
           110001

Splitting the multiplication this way is allowed because multiplication distributes over addition, that is what makes 001 * 111 + 010 * 111 + 100 * 111 equal to (001 + 010 + 100) * 111, and now it is obviously equal to 111 * 111.

like image 123
harold Avatar answered Oct 12 '22 23:10

harold