如何计算反向模量

时间:2012-08-31 15:36:15

标签: c# math formula reverse modulus

现在我有一个公式:

int a = 53, x = 53, length = 62, result;
result = (a + x) % length;

但如果已知结果已经

,如何计算反向模数以获得最小的“x”
(53 + x) % 62 = 44
//how to get x

我的意思是获得x

的公式或逻辑是什么

5 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:5)

它可能不是最初在模数中使用的X,但如果你有

(A + x) % B = C

你可以做到

(B + C - A) % B = x

答案 2 :(得分:1)

x = (44 - 53) % 62应该有用吗?

x = (44 - a) % length;

答案 3 :(得分:1)

怎么样

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

我现在知道这个答案是有缺陷的,因为它没有最小的但是.First()会解决这个问题。

答案 4 :(得分:0)

谁需要电脑?如果53 + x与44一致,模62,那么我们知道对于整数k,

53 + x + 62*k = 44

解决x,我们看到了

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

显然,最小的解是-9(当k = 0时)和53(当k = 1时)。

相关问题