0

我正在构建一个 C++ 程序来验证一个数学猜想,最多可进行 1000 亿次迭代。为了测试这么高的数字,我不能使用 a C++ int,所以我使用NTL库,使用类型ZZ作为我的数字类型。

我的算法如下所示:

ZZ generateNthSeq(ZZ n)
{
    return floor(n*sqrt(2));
}

我有两个要导入的库:

#include <cmath>
#include <NTL/ZZ.h>

但显然这无法编译,因为我收到错误:

$ g++ deepness*.cpp
deepness.cpp: In function ‘NTL::ZZ generateNthSeq(NTL::ZZ)’:
deepness.cpp:41: error: no matching function for call to ‘floor(NTL::ZZ)’
/usr/include/bits/mathcalls.h:185: note: candidates are: double floor(double)
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/cmath:262: note:                 long double std::floor(long double)
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/cmath:258: note:                 float std::floor(float)

说明地板数学运算不能接受 ZZ 类类型。但我需要数字相当大。如何在使用 NTL 库的同时完成我想要做的事情,即地板功能?

4

1 回答 1

4

请注意,应用于整数类型并没有真正意义floor(嗯,确实如此,它只是一个无操作)。您真正应该担心的是您的代码显然正在将某种类型的东西传递ZZfloor!

也就是说,n * sqrt(2)这里可能意味着什么?

此外,在编写之前,我已经检查了文档以查看库中是否真的存在 integer * 浮点数——通常为了让它有用,你需要可用的任意精度浮点类型。


检查标题,只有一个乘法运算符:

ZZ operator*(const ZZ& a, const ZZ& b);

并且有一个转换构造函数:

explicit ZZ(long a);  // promotion constructor

我无法弄清楚你的代码是如何编译的。也许您使用的库版本与我所看到的不同,并且转换构造函数是隐式的,并且您double正在“升级”为ZZ. 这肯定不是你想要的,因为提升sqrt(2)到 aZZ只会给你 integer 1

您要么需要:

  • 查看 NTL 是否具有任意精度浮点功能
  • 切换到具有任意精度浮点功能的库
  • 将您的计算转换为纯整数算术

最后一个在这里相当容易:你想要

return SqrRoot(sqr(n) * 2); // sqr(n) will be a bit more efficient than `n * n`
于 2015-05-27T17:00:14.170 回答