# Thread: Finding next largest integer multiple

1. ## Finding next largest integer multiple

Hi all. I recently stumbled across the following code:
Code:
```do
{
some_operation();
} while (++val & 7);```
What this (supposedly??) does is continuously call some_operation and increment val until val is an integer multiple of 8. I understand binary and use of the bitwise-operator, I just can't convince myself that this is 'true' for and works properly for all integer m such where (m*8) < val < (m+1)*8 . Is this some kind of trick only possible because 8 is a power of 2? The formula clearly does not work if we do (++val & 4) until val is a multiple of 5, as this test will fail for decimal values 1, 2, and 3..

Moreover, I need to expand this functionality for any integer n > 1, not just n = 8. Obviously the trivial solution is
Code:
```do
{
some_operation();
} while( (++val % m) != 0 );```
But I have had it burned into my head that the modulo operator is expensive. Is there a better, more efficient solution for this problem?

2. Originally Posted by Is there a better, more efficient solution for this problem?
Is there a better, more efficient solution for this problem?
Maybe it is sufficient to compute ((val / n) + 1) * n, assuming non-negative integer division, and that you really do want the next largest multiple of n even if val is perfectly divisible by n.

3. Ah, you mean something like:
Code:
```                next = ((val/n)+1)*n;
do{
something();
}
while( ++val < next );```
Yes, that seems to work as desired, and is somewhat more clear and flexible than the original.

Thanks!

Popular pages Recent additions