【发布时间】:2010-05-02 21:33:20
【问题描述】:
我正在为一个家庭作业项目编写一个小型 bignum 库。我要实现 Karatsuba 乘法,但在此之前我想编写一个幼稚的乘法例程。
我正在关注 Paul Zimmerman 编写的名为“现代计算机算术”的指南,该指南是 freely available online。
在第 4 页,有一个名为 BasecaseMultiply 的算法的描述,它执行小学乘法。
我理解第 2、3 步,其中 B^j 是 1、j 次的数字移位。 但我不明白第 1 步和第 3 步,我们有 A*b_j。如果 bignum 乘法还没有定义,这个乘法应该如何进行?
这个算法中的“*”操作会不会只是重复加法?
这是我到目前为止写的部分。我已经对它们进行了单元测试,因此它们在大多数情况下似乎是正确的:
我的 bignum 结构如下:
#define BIGNUM_DIGITS 2048
typedef uint32_t u_hw; // halfword
typedef uint64_t u_w; // word
typedef struct {
unsigned int sign; // 0 or 1
unsigned int n_digits;
u_hw digits[BIGNUM_DIGITS];
} bn;
当前可用的例程:
bn *bn_add(bn *a, bn *b); // returns a+b as a newly allocated bn
void bn_lshift(bn *b, int d); // shifts d digits to the left, retains sign
int bn_cmp(bn *a, bn *b); // returns 1 if a>b, 0 if a=b, -1 if a<b
【问题讨论】:
-
您可以尝试使 bignum 乘法例程递归,因为您需要执行 A*b_j。我不确定它会如何定义,所以它几乎不是一个答案,但它至少是一个想法。我相信有一个更好的解决方案。 :)
标签: c algorithm math bignum multiplication