How to convert last 3 digits of number into 0
example 3444678 to 3444000
I can do like
(int)(3444678/1000) * 1000= 3444000
But division and multiplication could be costly...
Any other solution????
You could try
n - (n % 1000)
but the modulus operator might be as costly as a division. In any case, this sounds an awful lot like a micro-optimization. Is this really your bottleneck?
A shift trick, then:
n >>= 3;
n -= n % (5 * 5 * 5);
n <<= 3;
Is it faster? Doubtful.
But here's a fun fact: gcc doesn't use division/modulus for this:
n -= n % 1000;
It multiplies by some crazy number (274877907) and does some other stuff which is presumably faster.
The moral of this story: the more obvious the purpose of your code is to the compiler, the more likely it is that the compiler will optimise it in a way you'd never think of. If the code is easier for humans to understand, that's another bonus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With