/*
书中的公式是w位的公式(mod 就是为了截断成w位),我们现在做的是2w位中的前w位
注意书上这句话:由于模运算符,所有带有权重和的项都丢掉
对应到本题
该项除以后还是超过了2w位所以被丢弃了,因为题目说了只有2w位
这个式子除以就是我们想要的最终结果
函数signed_high_prod 的结果((int64_t) x * y )>> 32
对应的是x*y/
函数unsigned_high_prod的结果中x * sig_y + y * sig_x
对应的是
*/
#include <stdio.h>
#include <stdint.h>
#define TMax 2147483647
#define TMin (-TMax - 1)
int signed_high_prod(int x, int y);
unsigned unsigned_high_prod(unsigned x, unsigned y);
int main(void)
{
unsigned x = 4294967295;
unsigned y = 4294967295;
printf("x*y\t\t%x\n",unsigned_high_prod(x,y));
}
int signed_high_prod(int x, int y)
{
printf("x*ysigned\t%8llx\n",(int64_t) x * y );
printf("x*ysigned>>\t%8llx\n",((int64_t) x * y )>> 32);
return ((int64_t) x * y )>> 32;
}
unsigned unsigned_high_prod(unsigned x, unsigned y) {
unsigned signed_prod = signed_high_prod(x, y);
int sig_x = x >> 31;//右移时x还是无符号所以能得到掩码
int sig_y = y >> 31;
return signed_prod + x * sig_y + y * sig_x;
}