c - 你能发现我在 Karatsuba 算法的 C 实现中犯的错误吗
问题描述
我需要将 karatsuba 算法实现为我的家庭作业的 ac 代码,我进行了研究并提出了以下代码:
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如果有人能发现我犯的错误,我会很高兴。
解决方案
所以问题是在长整数识别下,7位数字的乘法不正确。当我将其更改为 long long int 时,它开始正常工作。谢谢大家的帮助
推荐阅读
- java - Spring JPA 并按输入字段排序
- python - 在 Django REST 框架中,使用带有渲染器的 ModelViewSet,
- php - Convert an associative array into an associative array which has a key with another associative array as its value in php
- asp.net-mvc - 布尔值总是被认为是假的,但它在数据库中是真的吗?MVC
- neural-network - 性能不佳有助于人工神经网络的多类分类
- javascript - Rails 'local-time' gem 没有运行 JS
- apache-spark - spark sql-为sum函数提供列表参数
- typescript - Cypress:如何使用 cypress 文件夹中外部文件的绝对路径?
- r - 绘制平滑时间序列
- json - Flutter:将 50 多个模型类转换为支持 json_serializable 的快速方法