Is it possible to square a number stored in a register (say eax) without doing any multiplication (by using shifts, etc)? I will be squaring a 16-bit number in 32-bit assembly so overflow shouldn't be an issue. I am using NASM x86 assembly to create the program. Thanks in advance for your help.
In C:
int square(int n) {
int i, r = 0;
for (i = n; i; i >>= 1, n <<= 1)
if (i & 1)
r += n;
return r;
}
I'll leave the NASM to you.
Shift and Add is always a good starting point for doing multiplications on computers without involving multiplication instructions.
Precomputing a table is another option that could be suitable for this problem.
A little late answer. Here is the logic:- The square of N can be obtained by adding first N odd numbers.
In C,
int sqr(int num){
int j=1;
int sum=0;
while(num>0){
sum += j;
j += 2;
num--;
}
return sum;
}
but applicable only for integers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.