Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert last 3 digits of number into 0

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????

like image 885
anand Avatar asked Nov 30 '22 13:11

anand


2 Answers

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?

like image 189
Jesse Beder Avatar answered Dec 04 '22 09:12

Jesse Beder


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.

like image 31
Artelius Avatar answered Dec 04 '22 08:12

Artelius