C++-fmod返回错误的答案
C++ - fmod return the wrong answer
首先,我是为学校做这个项目的,我们不允许使用外部图书馆,因此我不能使用任何类似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比特长。所以,您遇到了截断错误。要做这个大的乘法和模,你需要对如何做幂和模更加聪明一点。
相关文章:
- 使用 bfs 解决连接组件问题时得到错误的答案
- 递归求和任务的错误答案
- 为什么我在代码厨师的 CMPRSS 问题中得到 WA(错误答案)?
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 函数从指针 c++ 中获取错误的值并返回错误的答案
- C ++分割错误,为什么使用"long long"我没有得到答案?
- 乘法宏给出错误的答案
- 谷歌启动B轮巴士路线问题错误的答案?
- 欧拉项目 #8 C++ 得到错误的答案
- 寻找最小楼梯成本的动态规划问题的错误答案
- 为什么可变大小的数组会导致Codechef出现错误答案
- 位集上的按位或给出错误的答案
- 在 c++ 中将模板与类一起使用时,类成员函数的答案错误?
- SPOJ PLD的答案错误
- UVA 3n+1(概率 100)答案错误,但所有测试用例均已通过
- 散列!!答案错误,想不通
- 指数的最后一位——答案错误
- 在计算cpp中数字的n次方根时,答案错误
- Euler项目27的答案错误