How to repeat number at a maximum?

2

I have two integers: n and m :

  • n : Number that will repeat in the index;
  • m : Index maximum.

What I need to do is simple, is to return a number that is <= m based on n . When n is greater, it will repeat how many times it "went out" of the maximum, for example:

10 repete 10 = 10
5  repete 10 = 5
15 repete 10 = 5
30 repete 10 = 10
11 repete 10 = 0
  

The minimum is 0 .

I set up this account in C # to return according to these values, but I was not successful:

    static int Rotate(int n, int m) {
        if (n <= m) return n;
        int d = n / m;
        n -= d * m;
        return n - 1;
    }

And the output of the above code, using the same repeated expressions in the above example were respectively:

10   -- correto
5    -- correto
4    -- errado
-1   -- errado
0    -- correto

In other words, when n is greater than m , it returns to index 0 and goes to whatever is left, repeating if it is greater than m :

15 repete 10:
m         = 0   1   2   3   4   5   6   7   8   9   10   0   1   2   4   5
n         = 1   2   3   4   5   5   6   7   8   9   10   11  12  13  14  15
resultado =                                                              ^^

How do I create a function to repeat these numbers at this maximum rate?

    
asked by anonymous 09.10.2017 / 20:22

1 answer

1

If I understand correctly, it is this logic that you want:

Note: Doing as you specified ("starting from zero index"), the values are not the same as those you showed. Note that in your question, in your last example, you skipped the number 3 of the m variable and doubled the number 5 of the n variable, but the result was to be another one, 4, instead of 5.

private static int Rotate(int n, int m)
{
    if(n <= m)
        return n;

    var auxM = 0;
    for (var i = 1; i <= n; i++)
    {
        if (auxM == m)
            auxM = 0;
        else
            auxM++;
    }

    return auxM;
}

See it working in .NET Fiddle

    
09.10.2017 / 20:48