question about Multiply high signed
#include <iostream>
using namespace std;
int mulths(int u,int v)
{
unsigned u0,v0,w0;
int u1,v1,w1,w2,t;
u0 = u & 开发者_如何学运维0xFFFF;
u1 = u >> 16;
v0 = v & 0xFFFF;
v1 = v >> 16;
w0 = u0 * v0;
t = u1 * v0 + (w0 >> 16);
w1 = t & 0xFFFF;
w2 = t >> 16;
w1 = u0 * v1 + w1;
return u1 * v1 + w2 + (w1 >> 16);
}
int main()
{
int u,v;
cin >> u >> v;
cout << mulths(u, v) << endl;
return 0;
}
does it returns product of two number yes or it returns most significant bit? beacuse when i enter 5 and 7 and it return 0
"Multiply high" returns the high word of the result. E.g. if ints are 32 bits then when you multiply two 32 bit ints you get a 64 bit result. So you can think of this as a 32 bit (signed) high word and a 32 bit (unsigned) low word. E.g. 0x01234567
x 0x456789AB
= 0x004EF78252247ACD
. High word (signed) = 0x004EF782
, low word (unsigned) = 0x52247ACD
.
For your test the values of 5 and 9 are too small and so the high word will be zero. Try larger values such as the above to see if you get the correct result, e.g.
$ g++ -m32 -Wall mulths.cpp -o mulths
$ ./mulths
1000
1000
0
$ ./mulths
100000
100000
2
$ ./mulths
19088743 # 0x01234567
1164413355 # 0x456789AB
5175170 # 0x004EF782
$
精彩评论