【发布时间】:2023-03-27 11:05:01
【问题描述】:
我需要将 karatsuba 算法实现为 c 代码以完成我的作业,我进行了研究并提出了以下代码:
long int karatsuba(long int x,long int y)
{
if((x<10)||(y<10)) \\if the numbers have 1 digit, I just multiply them
return x*y;
else
{
long int a, b, c, d, ac, bd, z;
int n=uzunluk(x);
a=floor(x/ust(10, ceil(n/2)));
b=x%ust(10, ceil(n/2));;
c=floor(y/ust(10, ceil(n/2)));
d=y%ust(10, ceil(n/2));;
ac=a*c;
bd=b*d;
z=(a+b)*(c+d)-ac-bd;
long int res=ust(10, 2*ceil(n/2))*ac+ust(10, ceil(n/2))*z+bd;
return res;
}
}
int main(void)
{
printf("%ld", karatsuba(837487, 368498));
return 0;
}
ust(x, n) 是求x次幂的函数:
long int ust(long x, long n)
{
long int res=1;
int i;
for(i=0; i<n; i++)
{
res*=x;
}
return res;
}
而 uzunluk(x) 获取给定输入的位数:
int uzunluk(long int x)
{
int lx;
while(x>0)
{
x/=10;
lx+=1;
}
return lx;
}
问题是这段代码什么也没打印:D 如果有人能发现我犯的错误,我会很高兴。
【问题讨论】:
-
没有检查你所有的代码,你的
uzunluk函数是错误的,因为它在计算中使用了未初始化的lx的值。 -
整数除法在
floor(x/ust(10, ceil(n/2)))中完成,结果被截断为整数,因此floor和ceil函数将无法按预期工作。跨度> -
除了实际算法中的错误,尝试在打印字符串的末尾添加字符
'\n'。printf因偶尔拒绝打印不以'\n'结尾的字符串而臭名昭著。因此该行最好是:printf("%ld\n", karatsuba(837487, 368498)); -
@MikeCAT 解决了不打印结果部分的问题,但现在它给出了错误的结果。打印的结果是一个负整数,我什至没有负输入:d
-
@MahmutMahmudov 请不要编辑您的代码来修复人们指出的错误。现在他们的 cmets 无效了。
标签: c algorithm multiplication karatsuba