Calculate square of a number without multiplication I wrote these two methods to calculate the square of a number:

static int sqr(int val)
{
    int valSqr = 0;

    for (int i = 0; i &lt; val; i++)
        valSqr += val;

    return valSqr;
}

static int sqr(int val)
{
    int valSqr = 0;

    for (int i = 0, j = 1; i &lt; val; i++, j += 2)
        valSqr += j;

    return valSqr;
}


The first one simply adds the given number to a value until it has been added number times.  The second one uses the 1+3+5... sequence.  I tried to profile this on Visual Studio, but the report was taking a really long time (over two hours) to be generated after the data collection was done.  I am particularly interested in which of these methods will run faster, and which is less resource intensive (would the second one be slightly more resource intensive because there are more variables?).
A more efficient way to do this is to keep doubling the product while you can....

So, for example, \$5^2\$ is:

$$\begin{eqnarray*}
 5 +&amp;  5 &amp;\longrightarrow 10 \\
 10 +&amp; 10 &amp;\longrightarrow 20
\end{eqnarray*} $$

then add the last 5 to get 25.

This can be done efficiently by using bit shifting:

public static int sqr (int val)
{
    int mask = 1;
    int factorsum = val;
    int sum = 0;
    while (val &gt;= mask)
    {
        if ((val &amp; mask) == mask)
        {
            sum += factorsum;
        }
        factorsum += factorsum;
        mask += mask;
    }
    return sum;
}


This is a \$O(\log(n))\$ solution to the problem. See it in ideone too