C++-fmod返回错误的答案

C++ - fmod return the wrong answer

本文关键字:答案 错误 返回 C++-fmod      更新时间:2023-10-16

首先,我是为学校做这个项目的,我们不允许使用外部图书馆,因此我不能使用任何类似GMP的东西。问题是,我有一个函数,它需要一些"艰难"的计算。即

m^e mod n

这是我的代码

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int e = 17, n = 3233, m = 65;
    long double p, mod;
    p = pow(m, e); // Gives 6.59974e+30 which is correct
    mod = fmodl(p, n);
    cout<<mod; // Gives 887, When the correct answer is 2790
    return 0;
}

正如你所看到的,fmod(fmodl)函数没有返回正确的值,有解决方法吗?同样,不使用任何外部库。

您可以编写自己的模幂函数。

int modpow(int a,int b,int mod)
{
    int product,pseq;
    product=1;
    pseq=a%mod;
    while(b>0)
    {
        if(b&1)
            product=(product*pseq)%mod;
        pseq=(pseq*pseq)%mod;
        b>>=1
    }
    return product;
}

请参阅http://en.wikipedia.org/wiki/Modular_exponentiation用于解释

您的代码正在使用这种简单的方法尽其所能。x86机器上的long double只有80位长,有大量的位专用于指数和符号

6517的精确值大约是103比特长。所以,您遇到了截断错误。要做这个大的乘法和模,你需要对如何做幂和模更加聪明一点。