2

TL;DR:

int remainder = -1 % 5; //-1
int modulus = -1 modulus 5; //4 How do I do this?

I am trying to read the modulated value of an array. So the index modulated by the array length would be the updated index. For example:

array = {100, 200, 300, 400, 500}
array[6] = array[6 mod 5] = array[1] = 200

Easy enough. But when my index is negative, that's where I get into trouble.

array[-1] = array[???] = array[4] = 500

I do not know how to perform -1 mod 5. The remainder operator works for positives, but not negatives.

Here is my sample code that only works for positive values:

static void Main(string[] args)
{
    int[] myArray = new int[5] { 100, 200, 300, 400, 500 };
    int myIndex = myArray.Length - 1;
    for (int i = 0; i < 15; i++)
    {
        myIndex = --myIndex % myArray.Length;
        Console.WriteLine("Value: " + myArray[myIndex]);
    }
    Console.WriteLine("Done");
}

How can I get the modulus of a number, not the remainder in C#?

Evorlor
  • 7,263
  • 17
  • 70
  • 141
  • Actually, the remainder operator *does* work for negatives, The remainder of dividing -1 by 5 is -1, simply because `-1/5` is 0, and `-1` is the difference between `0*5` and `-1`. The problem is that you want something else than what this operator provides. – Lasse V. Karlsen Jul 11 '17 at 20:00
  • 1
    The simplest way would be to do a double remainder calculation: `a % b` --> `((a % b) + b) % b`. – Lasse V. Karlsen Jul 11 '17 at 20:01
  • 1
    See [linked answer](https://stackoverflow.com/a/1082938/580951). – Dustin Kingen Jul 11 '17 at 20:04

1 Answers1

1

I think what you want to achieve is this:

var newIndex = myIndex % myArray.Length;
if (newIndex < 0) 
{
    newIndex += myArray.Length;
}

Does it do what you want?

I am also confused by your usage of 'modulus'. As far as I know, modulus is an absolute value. In order to get it, simply use

var modulus = Math.Abs(value)
Vlad Stryapko
  • 1,035
  • 11
  • 29
  • Errr, yes. That is what I use. I was hoping for a more elegant solution. I suspected that C# would have some sort of modulus operator, but I could be wrong. – Evorlor Jul 11 '17 at 19:57
  • @edit: The modulus is not the absolute value. https://stackoverflow.com/a/13683709/1889720 – Evorlor Jul 11 '17 at 19:58