round to the nearest power of 4

N

naren2345

Would this expression round an integer n to the nearest power of 4 ?

((n-1)|3) + 1
 
G

Guest

Would this expression round an integer n to the nearest power of 4 ?

((n-1)|3) + 1

No. Just try it with some simple numbers (1 through 10), then you'll
get an idea of what it's supposed to do (but doesn't always get right).
 
B

Bob Martin

in said:
Would this expression round an integer n to the nearest power of 4 ?

((n-1)|3) + 1

add 3 then lose 2 low-order bits by shifting (note my assembler background?)
 
R

Richard Bos

Would this expression round an integer n to the nearest power of 4 ?

((n-1)|3) + 1

No, it rounds to something-else of 4.

Also, for powers, define "nearest": arithmetically, geometrically, or
unusually?

Richard
 
D

David T. Ashley

Would this expression round an integer n to the nearest power of 4 ?

((n-1)|3) + 1

You need to define what you mean by "power" and by "round" and by "nearest".

Did you actually mean "multiple" (0, 4, 8, 12, 16, etc.)?

Or did you actually mean "power" (1, 4, 16, 64, etc.)?

Looking at your code ...

0 --> 0
1 --> 4
2 --> 4
3 --> 4
4 --> 4
5 --> 8
6 --> 8

So in some sense it does round to a near muliple (not power!) of 4. But not
the nearest one.

There are an endless variety of code constructs, depending on how efficient
one needs to be. Certainly

switch (n & 3)

comes to mind as a starting point.

Dave.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top