patterncsharpMajor
Calculate square of a number without multiplication
Viewed 0 times
withoutnumbermultiplicationcalculatesquare
Problem
I wrote these two methods to calculate the square of a number:
The first one simply adds the given number to a value until it has been added
static int sqr(int val)
{
int valSqr = 0;
for (int i = 0; i < val; i++)
valSqr += val;
return valSqr;
}
static int sqr(int val)
{
int valSqr = 0;
for (int i = 0, j = 1; i < 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?).Solution
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 +& 5 &\longrightarrow 10 \\
10 +& 10 &\longrightarrow 20
\end{eqnarray*} $$
then add the last 5 to get 25.
This can be done efficiently by using bit shifting:
This is a \$O(\log(n))\$ solution to the problem. See it in ideone too
So, for example, \$5^2\$ is:
$$\begin{eqnarray*}
5 +& 5 &\longrightarrow 10 \\
10 +& 10 &\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 >= mask)
{
if ((val & 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
Code Snippets
public static int sqr (int val)
{
int mask = 1;
int factorsum = val;
int sum = 0;
while (val >= mask)
{
if ((val & mask) == mask)
{
sum += factorsum;
}
factorsum += factorsum;
mask += mask;
}
return sum;
}Context
StackExchange Code Review Q#74296, answer score: 20
Revisions (0)
No revisions yet.