math - Triple Modular Multiplicaiton -
i calculating following sum:
(a[x]+ma[x-1]+2ma[x-2]+3m*a[x-3]+....)%mod (mod=1e9+7)
for this, using loop.
long long mulmod(long long a,long long b,long long c) { if (a == 0 || b == 0) return 0; if (a == 1) return b; if (b == 1) return a; long long a2 = mulmod(a, b / 2, c); if ((b & 1) == 0) { return (a2 + a2) % c; } else { return ((a % c) + (a2 + a2)) % c; } } res=a[x]%mod; for(i=x-1;i>=1;i--) res=(res%mod+mulmod(mulmod(x-i,m,mod),a[i],mod))%mod;
however, still giving me overflow errors. basic error, guess in (abc)%mod.
thank you.
you need incorporate following modular arithmetic identities program avoid overflow:
(a + b + ...) mod c = (a mod c + b mod c + ... mod c) mod c
and
(a * b * ...) mod c = (a mod c * b mod c * ... mod c) mod c
Comments
Post a Comment