math - C++ - fmod return the wrong answer -
first off, i'm doing project school , not allowed use external libraries , hence cannot use gmp. problem is, have function requires "tough" calculations. ie,
m^e mod n
here's code
#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 correct mod = fmodl(p, n); cout<<mod; // gives 887, when correct answer 2790 return 0; }
as can see fmod (fmodl) function not return correct value there workaround ? again, without using external libraries.
you can write own modulo power function.
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; }
refer http://en.wikipedia.org/wiki/modular_exponentiation explanation
Comments
Post a Comment