473,765 Members | 2,061 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
17 21602
On 9/28/2003 1:21 PM, Matt wrote:
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


if (!(x%2)) {
puts("x is a power of 2");
}

Regards,

Ed.

Nov 13 '05 #11
Ed Morton wrote:
On 9/28/2003 1:21 PM, Matt wrote:
Give a one-line C expression to test whether a number is a power of 2.
No loops allowed.


if (!(x%2)) {
puts("x is a power of 2");
}


Are you implying that 42 is a power of 2 and 43 is not?
BTW: It's a three-liner and no C expression at all. ;-)

Jirka

Nov 13 '05 #12


On 9/29/2003 10:44 AM, Jirka Klaue wrote:
Ed Morton wrote:
On 9/28/2003 1:21 PM, Matt wrote:

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


if (!(x%2)) {
puts("x is a power of 2");
}

Are you implying that 42 is a power of 2 and 43 is not?
BTW: It's a three-liner and no C expression at all. ;-)

Jirka


I had intended !(x%2) to be the expression, the rest was demonstrating using it.
I'll go back to sleep now.... wake me next time you want to know if a number is
a multiple of 2 rather than a power of 2. Sorry 'bout that.

Ed.

Nov 13 '05 #13
Joona I Palaste <pa*****@cc.hel sinki.fi> wrote:

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

What do I win?


Nothing. What if x is negative? What if it's not an integer? What if
the original poster provided a complete specification of the problem? :-)

-Larry Jones

I kind of resent the manufacturer's implicit assumption
that this would amuse me. -- Calvin
Nov 13 '05 #14
Eric Sosman <Er*********@su n.com> wrote in message news:<3F******* ********@sun.co m>...
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.)


Why stop there? C99 has complex types. ;)

--
Peter
Nov 13 '05 #15
Ed Morton wrote:
On 9/28/2003 1:21 PM, Matt wrote:
Give a one-line C expression to test whether a number is a
power of 2. No loops allowed.


if (!(x%2)) {
puts("x is a power of 2");
}

^^^^^^^^^^^^
even

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 13 '05 #16
Da*****@cern.ch (Dan Pop) wrote in message news:<bl******* ***@sunnews.cer n.ch>...
...
Now, !!x is an obfuscated way of writing 1, when you know that x cannot
be zero (it was already tested)


this is exactly what i got stuck in :-) i should have guessed it ...
thanks for the explanation though :-)
Nov 13 '05 #17
"jacob navia" <ja*********@ja cob.remcomp.fr> wrote in message news:<bl******* ***@news-reader5.wanadoo .fr>...
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.


Few Mathematicians say any positive integer raised to the power minus
infinity is 0. That is,
n (pow) (-infinity) = 0

IOW, 2 (pow) 3 = 8, 2 (pow) 2 = 4, 2 (pow) 1 = 2, 2 (pow) 0 = 1,
and, 2 (pow) (-infinity) = 0.

Because of this religious reason, I would just write my macro as
(without 0 check)
#define ISPOWOF2( n ) ( ! ( n & (n-1) ) )

But, someone here in CLC told me that the above macro won't work all
the time. I know, it won't work for float; I know the necessity of
additional paranthesis for n. But, I couldn't see any other reasons.
Anybody have any good comments? TIA

---
"Silence is the only right answer for many wrong questions" --
G.K.Moopanaar, Indian Politician
http://guideme.itgo.com/atozofc/ - "A to Z of C" Project
Email: rrjanbiah-at-Y!com
Nov 13 '05 #18

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

Similar topics

11
8457
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
4939
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
10739
by: ravi | last post by:
Give a one-line C expression to test whether a number is a power of 2.
0
9568
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
9399
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
10163
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...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9835
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
8832
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...
0
6649
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();...
0
5276
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3532
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.