473,748 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

test whether a number is a power of 2

Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.
Nov 13 '05 #1
17 21598
Matt <jr********@hot mail.com> scribbled the following:
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


((((x&&!(x&(x-!!x)))+x)-x)^x)^x

What do I win?

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"Remember: There are only three kinds of people - those who can count and those
who can't."
- Vampyra
Nov 13 '05 #2
"Matt" <jr********@hot mail.com> wrote in message
news:ba******** *************** ***@posting.goo gle.com...
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


isPow2 = x && !( (x-1) & x );

See http://www.caam.rice.edu/~dougm/twiddle/
for some related info.

hth
--
http://ivan.vecerina.com
http://www.brainbench.com <> Brainbench MVP for C++


Nov 13 '05 #3
jr********@hotm ail.com (Matt) writes:
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


We're not here to do your homework for you.

--
Keith Thompson (The_Other_Keit h) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #4
isPow2 = x && !( (x-1) & x );


Algorithm:
If x is a power of two, it doesn't have any bits in common with x-1, since it
consists of a single bit on. Any positive power of two is a single bit, using
binary integer representation.

This means that we test if x-1 and x doesn't share bits with the and operator.

Of course, if x is zero (not a power of two) this doesn't hold, so we add an
explicit test for zero with xx && expression.

Negative powers of two (0.5, 0.25, 0.125, etc) could share this same property
in a suitable fraction representation. 0.5 would be 0.1, 0.250 would be 0.01,
0.125 would be 0.001 etc.

jacob
Nov 13 '05 #5
Joona I Palaste <pa*****@cc.hel sinki.fi> wrote in message news:<bl******* ***@oravannahka .helsinki.fi>.. .
Matt <jr********@hot mail.com> scribbled the following:
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


((((x&&!(x&(x-!!x)))+x)-x)^x)^x

What do I win?

hi Joona,

i know this works because i just tested it .. but help me understand
the algoritm please ..

Thanks and Regards
A.
Nov 13 '05 #6
Matt wrote:

Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


true_or_false = a_number > 0;

(For example, 3.14159 ~= 2 ** 1.65149.)

--
Er*********@sun .com
Nov 13 '05 #7
In <64************ *************@p osting.google.c om> ai*******@sapie nt.com (Aishwarya) writes:
Joona I Palaste <pa*****@cc.hel sinki.fi> wrote in message news:<bl******* ***@oravannahka .helsinki.fi>.. .
Matt <jr********@hot mail.com> scribbled the following:
> Give a one-line C expression to test whether a number is a power of 2.
> No loops allowed.


((((x&&!(x&(x-!!x)))+x)-x)^x)^x


i know this works because i just tested it .. but help me understand
the algoritm please ..


Had you engaged your brain, you'd have easily noticed that one ^x cancels
the other and that -x cancels the +x, so you're left with

x&&!(x&(x-!!x))

Now, !!x is an obfuscated way of writing 1, when you know that x cannot
be zero (it was already tested), so, we're left with:

x&&!(x&(x-1))

The tricky bit is x&(x-1) which actually clears the least significant
bit that happens to be set. If the original number was a power of two,
it had only one bit set, so the result of x&(x-1) must be zero in such
cases.

The rest should be obvious.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #8
In <lz************ @cts.com> Keith Thompson <ks*@cts.com> writes:
jr********@hot mail.com (Matt) writes:
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


We're not here to do your homework for you.


OTOH, the solution is far too tricky for a homework assignment. It
requires a bit of knowledge that has precious little to do with C
programming.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #9
Aishwarya wrote:
Joona I Palaste <pa*****@cc.hel sinki.fi> wrote in message news:<bl******* ***@oravannahka .helsinki.fi>.. .

....
((((x&&!(x& (x-!!x)))+x)-x)^x)^x


i know this works because i just tested it .. but help me understand
the algoritm please ..


+x -x does nothing, ^x ^x does nothing.

remains:
x && !(x & (x - !!x))

!!x ist alway 1, because x can't be 0 at this point.

remains:
x && !(x & (x - 1))

Jirka

Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
8455
by: MJ | last post by:
Hi I have question about the C. I have a number X which is power of two X = 2 power n I need to find it using a Single C statement whether its a power of 2 or not I know that a number with power of 2 will have only one single bit as 1 and rest of the bit as 0. To check the bit I need to go through all the bits ones and check for the condition. I dont want use a loop. In that case how can I do this
10
4936
by: David T. Ashley | last post by:
What is the most economical test in 'C' for "integer is a power of 2"? For example, something better than: void is_2_pow(int arg) { return((x == 1) || (x == 2) || (x == 4) || (x == 8) || (x == 16) /* and so on */ ); }
20
10734
by: ravi | last post by:
Give a one-line C expression to test whether a number is a power of 2.
0
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9333
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8255
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6799
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.