how to calculate reverse modulus

心不动则不痛 提交于 2019-11-28 01:59:42
private int ReverseModulus(int div, int a, int remainder)
{
   if(remainder >= div)
      throw new ArgumentException("Remainder cannot be greater than or equal to divisor");
   if(a < remainder)
      return remainder - a;
   return div + remainder - a;
}

e.g. :

// (53 + x) % 62 = 44
var res = ReverseModulus(62,53,44); // res = 53

// (2 + x) % 8 = 3
var res = ReverseModulus(8,2,3); // res = 1

It may not be the X that was originally used in the modulus, but if you have

(A + x) % B = C

You can do

(B + C - A) % B = x

x = (44 - 53) % 62 should work?

x = (44 - a) % length;

how about

IEnumerable<int> ReverseModulo(
    int numeratorPart, int divisor, int modulus)
{
   for(int i = (divisor + modulus) - numeratorPart; 
       i += divisor; 
       i <= int.MaxValue)
   {
       yield return i;
   }
}

I'm now aware this answer is flawed because it does not gice the smallest but a .First() would fix that.

Who needs a computer? If 53 + x is congruent to 44, modulo 62, then we know that for integer k,

53 + x + 62*k = 44

Solving for x, we see that

x = 44 - 53 - 62*k = -9 - 62*k

Clearly the smallest solutions are -9 (when k=0) and 53 (when k=1).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!