7

now I have one formula:

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

but how to calculate reverse modulus to get the smallest "x" if I known result already

(53 + x) % 62 = 44
//how to get x

i mean what's the formula or logic to get x

Erwin
  • 4,757
  • 3
  • 31
  • 41
Ivan Li
  • 1,850
  • 4
  • 19
  • 23

5 Answers5

12
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
digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • 1
    @Ivan Li: his `div + remainder - a` is my `B + C - A`. If mine doesn't work with other numbers, neither would this. – Corey Ogburn Aug 31 '12 at 16:07
  • In that case, no answers work. I'm not trying to discredit your answer @digEmAll, I just feel a little shafted for having the same basic equation as you (12 mins before you), just without the obvious validation. – Corey Ogburn Aug 31 '12 at 16:12
  • However, is it correct to consider the smallest positive x ? Otherwise the smallest in your example should be -9, not 53 ... – digEmAll Aug 31 '12 at 16:12
  • @CoreyOgburn: actually that's what my if condition handles. `(2 + 1) % 8 = 3` and `remainder - a` yields exactly 1... while the equal part of our codes gives 9... – digEmAll Aug 31 '12 at 16:14
  • You got me there, I didn't think about that. My edit now accounts for it all in one equation, but I do owe that to you. – Corey Ogburn Aug 31 '12 at 16:17
5

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

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
  • Nevermind, @digEmAll's answer points out where mine fails. Editted to account for that. – Corey Ogburn Aug 31 '12 at 16:19
  • this of course is the first and good answer, but @digEmAll's straightforwardly solves my problem with if statement handling. but anyway, thanks, you guys help me a lot. – Ivan Li Aug 31 '12 at 16:30
1

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

x = (44 - a) % length;
TheHe
  • 2,933
  • 18
  • 22
1

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.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
0

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).