0

I know that (a*b)%m is equal to ((a%m)*(b%m))%m?

But how to calculate a%(m*m)?

ChilliDoughnuts
  • 367
  • 2
  • 13
  • 2
    If `m * m` can overflow then your result can be bigger than the maximum representable value. How to you plan to deal with that? Also, do note that `(a % m) * (b % m)` can overflow too if `m * m` is too big. – eesiraed Aug 02 '19 at 18:06
  • You might ask on [the Math SE](http://math.stackexchange.com/tour) for equivalents of that expression. – Some programmer dude Aug 02 '19 at 18:07
  • Have a look at [GMP](https://gmplib.org/) (and similar libraries). – Jesper Juhl Aug 02 '19 at 18:11
  • 6
    If `k*k` *would* overflow, it would be greater than `n` and the modulo operation should do nothing. Detecting that and doing nothing isn't too hard – harold Aug 02 '19 at 18:40
  • 1
    Please provide constraints on the size of `a` and `m`. – Mikhail Aug 02 '19 at 19:18

1 Answers1

1

We need to calculate a%(m*m) without causing integer overflow.

long long int a, m, sqrt_a, ans;
sqrt_a = sqrt(a);
if (sqrt_a < m) {
    ans = a; // since "m > sqrt_a" then a%(m*m) will be "a"
}
else {
   ans = a % (m*m); // since "m <= sqrt_a" then m*m won't cause overflow
}

Kamol Hasan
  • 12,218
  • 1
  • 37
  • 46