因此,我决定尝试用C++实现Karatsuba的算法(自从我上第二节编程课以来,我就再也没有用过这种语言了,所以我非常非常生疏)。不管怎样,我相信我已经逐行跟踪了伪代码,但我的算法仍然不断地弹出错误的答案。
x = 1234, y = 5678
Actual Answer: x*y ==> 7006652
Program output: x*y ==> 12272852*注意:我在mac上运行,并使用以下代码创建运行c++ -std=c++11 -stdlib=libc++ karatsuba.cpp的可执行文件
不管怎样,这是我起草的代码,你可以随意指出我做错了什么,或者如何改进c++。
谢谢!
代码:
#include <iostream>
#include <tuple>
#include <cmath>
#include <math.h>
using namespace std;
/** Method signatures **/
tuple<int, int> splitHalves(int x);
int karatsuba(int x, int y, int n);
int main()
{
int x = 5678;
int y = 1234;
int xy = karatsuba(x, y, 4);
cout << xy << endl;
return 0;
}
int karatsuba(int x, int y, int n)
{
if (n == 1)
{
return x * y;
}
else
{
int a, b, c, d;
tie(a, b) = splitHalves(x);
tie(c, d) = splitHalves(y);
int p = a + b;
int q = b + c;
int ac = karatsuba(a, c, round(n / 2));
int bd = karatsuba(b, d, round(n / 2));
int pq = karatsuba(p, q, round(n / 2));
int acbd = pq - bd - ac;
return pow(10, n) * ac + pow(10, round(n / 2)) * acbd + bd;
}
}
/**
* Method taken from https://stackoverflow.com/questions/32016815/split-integer-into-two-separate-integers#answer-32017073
*/
tuple<int, int> splitHalves(int x)
{
const unsigned int Base = 10;
unsigned int divisor = Base;
while (x / divisor > divisor)
divisor *= Base;
return make_tuple(round(x / divisor), x % divisor);
}发布于 2020-07-12 09:21:47
你的代码中有很多问题...
首先,这里的系数是错误的:
int q = b + c;必须是:
int q = c + d;接下来,splitHalves的实现不会完成这项工作。试一试:
tuple<int, int> splitHalves(int x, int power)
{
int divisor = pow(10, power);
return make_tuple(x / divisor, x % divisor);
}这将为您的输入提供“正确”答案,但是...这不是Karatsuba方法。
首先,记住你不需要“一分为二”。考虑12 * 3456。将第一个数字一分为二意味着a = 0,b = 12,而您的实现给出了a = 1,b = 2。
总的来说,Karastuba使用数组,而不是整数。
https://stackoverflow.com/questions/62855785
复制相似问题