Faster modulus in C/C#?

后端 未结 7 1065
情话喂你
情话喂你 2020-12-25 13:07

Is there a trick for creating a faster integer modulus than the standard % operator for particular bases?

For my program, I\'d be looking for around 1000-4000 (e.g.

相关标签:
7条回答
  • 2020-12-25 13:40

    Here's a few techniques that replicate the modulus operation.

    Of those benchmarked, this was the fastest (modified to fit your 2048 scenario). As long as your "max" isn't millions and in the 1000-4000 range you mentioned, it may work faster for you too:

    int threshold = 2048; //the number to mod by
    int max = 1000; //the number on the left. Ex: 1000 % 2048
    int total = 0;
    int y = 0;
    for (int x = 0; x < max; x++)
    {
        if (y > (threshold - 1))
        {
            y = 0;
            total += x;
        }
        y += 1;
    }
    return total;
    

    Give it a go. It performed faster on the author's machine at various settings, so should perform admirably well for you too.

    0 讨论(0)
提交回复
热议问题