Home > Blockchain >  What is the correct way of doing modulo 10^9 7?
What is the correct way of doing modulo 10^9 7?

Time:10-27

How to get the correct modulo for the following piece of code. I am stuck here. I am using typecasts to get my result. I need to return int. What is the correct way.

int m = 1000000007;
long res=0L;
if(numOne > 3)
  res = (parts[1] - parts[0]) * (parts[3] - parts[2]);
return (int)res%m;  

parts array store integers, res is long. The above multiplication result gets overflowed and thus res turns negative. Without typecasting what is the best way of doing so..

res = (long)(parts[1] - parts[0]) * (long)(parts[3] - parts[2]);

The above code works fine.

CodePudding user response:

Use modulo before multiplication as your current implementation might overflow in some cases:

int m = 1000000007;
long res = 0L;
if (numOne > 3)
    res = ((parts[1] - parts[0]   m) % m) * ((parts[3] - parts[2]   m) % m);
return res % m;

Reference: here

CodePudding user response:

To avoid overflow, you need need to apply the mod to each side of the multiplication and cast each side of the multiplication to long (or better, change parts to be an array of long)

res = (long)(parts[1] - parts[0])%m * (long)(parts[3] - parts[2])%m;

CodePudding user response:

Use utility function for modular operations. And cast ints to longs before any operation.

long mod(long n){
   return (a % m   m) % m;
}
res = mod(mod((long)parts[1] - parts[0]) * mod((long)parts[3] - parts[2]));
  • Related