473,765 Members | 2,061 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

to 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]

Jul 8 '07
20 10739
In article <pi************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>Eric Sosman wrote, On 08/07/07 13:27:
>ravi wrote:
>>On Jul 8, 10:22 am, Martin Ambuhl <mamb...@earthl ink.netwrote:
ravi wrote:
Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed]
>Probably. Had you enough sense you would have instantly known the answer
was:
>int powerof2( double num ) { return 1; }
>After all, the OP did not specify integer power of 2, or even real power
of 2, and I think if you allow complex powers, all numbers will qualify.
But the OP did specify that the expression be one-line. Even if we
were to restrict our use of "number" to "the numbers representable
in C", since C does not have any run-time typing (RTT), I don't think
it would be possible to write a one-line expression that would take
an arbitrary number (of -any- of the valid C numeric types) as parameter
and return any meaningful information about it. If we could at least
receive the number as a void* and a type indicator, we could unionize
and ?: the problem to death.
--
Programming is what happens while you're busy making other plans.
Jul 10 '07 #11
Walter Roberson wrote:
>
In article <pi************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
Eric Sosman wrote, On 08/07/07 13:27:
ravi wrote:
On Jul 8, 10:22 am, Martin Ambuhl <mamb...@earthl ink.netwrote:
ravi wrote:
Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed]
[...]
int powerof2( double num ) { return 1; }
After all, the OP did not specify integer power of 2, or even real power
of 2, and I think if you allow complex powers, all numbers will qualify.

But the OP did specify that the expression be one-line. Even if we
were to restrict our use of "number" to "the numbers representable
in C", since C does not have any run-time typing (RTT), I don't think
it would be possible to write a one-line expression that would take
an arbitrary number (of -any- of the valid C numeric types) as parameter
and return any meaningful information about it. If we could at least
receive the number as a void* and a type indicator, we could unionize
and ?: the problem to death.
Why not a macro?

#define POWEROF2(value) (1)

However, can zero be expressed as a power of 2? (I suppose raising 2
to the power of negative infinity may qualify, but I'm not certain.)

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Jul 10 '07 #12
In article <pi************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>Had you enough sense you would have instantly known the answer
was:
>int powerof2( double num ) { return 1; }
>After all, the OP did not specify integer power of 2, or even real power
of 2, and I think if you allow complex powers, all numbers will qualify.
Hey, I just realized that the specification required that the
expression -test- that the number was a power of 2, but the
specification didn't require that the expression evaluated to
anything in particular either way -- or even that the expression
got the test right in any or all cases.

For example, we commonly speak of "testing whether a number is prime"
and in a number of cases are satisfied if the test is looking for
"obvious" non-primes, something fast as a filter to keep us from
having to use slower but more complete algorithms.
--
Is there any thing whereof it may be said, See, this is new? It hath
been already of old time, which was before us. -- Ecclesiastes
Jul 10 '07 #13
Kenneth Brody wrote, On 10/07/07 18:52:
Walter Roberson wrote:
>In article <pi************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>>Eric Sosman wrote, On 08/07/07 13:27:
ravi wrote:
On Jul 8, 10:22 am, Martin Ambuhl <mamb...@earthl ink.netwrote:
>ravi wrote:
>>Give a one-line C expression to test whether a number is a power of 2.
>> [No loops allowed]
[...]
>>int powerof2( double num ) { return 1; }
After all, the OP did not specify integer power of 2, or even real power
of 2, and I think if you allow complex powers, all numbers will qualify.
But the OP did specify that the expression be one-line. Even if we
were to restrict our use of "number" to "the numbers representable
in C", since C does not have any run-time typing (RTT), I don't think
it would be possible to write a one-line expression that would take
an arbitrary number (of -any- of the valid C numeric types) as parameter
and return any meaningful information about it. If we could at least
receive the number as a void* and a type indicator, we could unionize
and ?: the problem to death.

Why not a macro?

#define POWEROF2(value) (1)

However, can zero be expressed as a power of 2? (I suppose raising 2
to the power of negative infinity may qualify, but I'm not certain.)
You could check for 0 then.
#define POWEROF2(value) ((value)!=0)

Hard to do something that will cope with inf and NaN for both complex
and doubles in C99, but we could lobby for adding type-generic versions
of isnan and isinf to C0x to solve this problem.
--
Flash Gordon
Jul 10 '07 #14
Walter Roberson wrote, On 10/07/07 19:09:
In article <pi************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>Had you enough sense you would have instantly known the answer
was:
>int powerof2( double num ) { return 1; }
>After all, the OP did not specify integer power of 2, or even real power
of 2, and I think if you allow complex powers, all numbers will qualify.

Hey, I just realized that the specification required that the
expression -test- that the number was a power of 2,
See elsethread where I added some tests. Specifically for inf, NaN and 0.
but the
specification didn't require that the expression evaluated to
anything in particular either way -- or even that the expression
got the test right in any or all cases.
OK, replace the 1 by (num!=atan(num) )
For example, we commonly speak of "testing whether a number is prime"
and in a number of cases are satisfied if the test is looking for
"obvious" non-primes, something fast as a filter to keep us from
having to use slower but more complete algorithms.
Oh, you were thinking of the less accurate test being faster. <shrug>
Well, that was not in the original spec either.
--
Flash Gordon
Jul 10 '07 #15
Flash Gordon <sp**@flash-gordon.me.ukwri tes:
Kenneth Brody wrote, On 10/07/07 18:52:
[...]
>Why not a macro?
#define POWEROF2(value) (1)
However, can zero be expressed as a power of 2? (I suppose raising 2
to the power of negative infinity may qualify, but I'm not certain.)

You could check for 0 then.
#define POWEROF2(value) ((value)!=0)
Or, more simply:

#define POWEROF2(value) (value)

Both forms have the interesting property of treating non-null pointers
as powers of 2.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 10 '07 #16
ravi wrote:
>
Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed]
int n_is_Power_of_t wo(long unsigned n)
{
return (n & n - 1) == 0 && n != 0;
}

int n_is_Power_of_f our(long unsigned n)
{
return (n & n - 1) == 0 && n % 3 == 1;
}

int n_is_Power_of_e ight(long unsigned n)
{
return (n & n - 1) == 0 && n % 7 == 1;
}

--
pete
Jul 10 '07 #17
Keith Thompson wrote, On 10/07/07 21:49:
Flash Gordon <sp**@flash-gordon.me.ukwri tes:
>Kenneth Brody wrote, On 10/07/07 18:52:
[...]
>>Why not a macro?
#define POWEROF2(value) (1)
However, can zero be expressed as a power of 2? (I suppose raising 2
to the power of negative infinity may qualify, but I'm not certain.)
You could check for 0 then.
#define POWEROF2(value) ((value)!=0)

Or, more simply:

#define POWEROF2(value) (value)

Both forms have the interesting property of treating non-null pointers
as powers of 2.
Perhaps that will help those people who want to do strange things
because the believe (incorrectly) that pointers are just integers then :-)
--
Flash Gordon
Jul 10 '07 #18
Christopher Benson-Manica wrote:
CBFalconer <cb********@yah oo.comwrote:
[OP wrote:]
>>Give a one-line C expression to test whether a number is a power
of 2.
>I like my version better :-) In all seriousness, this is not such
a simple thing, so I doubt it was homework. If he hadn't used such
rude terminology I would be virtually sure it is not.

Given the number of ridiculous questions that are routinely asked here
that clearly *are* homework, I'm surprised you find it unlikely that
the above question is not homework. Why else would there be
constraints such as "one line" or "no loops allowed" (snipped from
above context)? I personally find it highly unlikely that anyone
asking the question seriously would phrase it so tersely.
You have a definite point, and are probably right.

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfoc us.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jul 11 '07 #19
On Mon, 09 Jul 2007 08:13:20 +0100, Flash Gordon wrote:
Harald van Dijk wrote, On 08/07/07 23:37:
>Flash Gordon wrote:
>>Probably. Had you enough sense you would have instantly known the answer
was:

int powerof2( double num ) { return 1; }

After all, the OP did not specify integer power of 2, or even real power
of 2, and I think if you allow complex powers, all numbers will qualify.

What about zeroes, infinities, and NaNs? I would think it should return 0
for those.

Zero is easy to deal with, infinities could be argued as being powers of
2, [snip]
The argument about infinities also applies to zero. The difference
is just the sign of the exponent.

--
Army1987 (Replace "NOSPAM" with "email")
"Never attribute to malice that which can be adequately explained
by stupidity." -- R. J. Hanlon (?)

Jul 13 '07 #20

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

Similar topics

17
21602
by: Matt | last post by:
Give a one-line C expression to test whether a number is a power of 2. No loops allowed.
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 */ ); }
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
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...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
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.