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

时间:2013-08-10 06:05:40

标签: c++ math

首先,我正在为学校做这个项目,我们不允许使用外部库,因此我不能使用像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)函数没有返回正确的值是否有解决方法?再次,不使用任何外部库。

2 个答案:

答案 0 :(得分:2)

您可以编写自己的模幂功能。

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了解

答案 1 :(得分:1)

使用这种简单的方法,您的代码正在尽力而为。 x86计算机上的long double只有80位长,并且有很多位专用于指数和符号。

65 17 的确切值约为103位长。所以,你遇到了截断错误。要做到这个大的乘法和模数,你需要更加智能地了解你的取幂和模数。