How to repeat number at a maximum?

Asked

Viewed 213 times

2

I have two whole: 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 on the basis of n. When n is larger, it will repeat how many times "came out" of 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 unsuccessful:

    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 expressions repeated 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 goes back to the index 0 and go to what’s left, repeating if it’s bigger 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 in this maximum index?

  • but when the repetition will pause? what is the condition of leaving? If not your code will bugar

  • It will pause when the repetition of the index is over.

1 answer

1


If I understand correctly, it’s this logic you want:

Obs.: Doing as you specified ("from zero index"), the values are not equal to those you showed. Note that in your question, in your last example, you skipped the variable number 3 m and doubled the number 5 of the variable n, the result, however, was to have been another, 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 working on . NET Fiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.