C program to display the number if it is a power of 2 in an array
#include <stdio.h>
#include <math.h>
int main()
int num,i;
scanf("%d",&num);
int a[num];
for (i=0; i<num; i++)
scanf("%d",&a[i]);
for (i=0; i<num+1; i++)
if (pow(2,i) == a[i])
printf("%dn",a[i]);
I am trying to create a program that displays an integer in an array if it is a power of two. ex; an array contains the integer (1,2,4,9) it will print 1,2 and 4 only.
What is wrong with this code? It works on some test cases, but on most it doesn't.
c pow
|
show 1 more comment
#include <stdio.h>
#include <math.h>
int main()
int num,i;
scanf("%d",&num);
int a[num];
for (i=0; i<num; i++)
scanf("%d",&a[i]);
for (i=0; i<num+1; i++)
if (pow(2,i) == a[i])
printf("%dn",a[i]);
I am trying to create a program that displays an integer in an array if it is a power of two. ex; an array contains the integer (1,2,4,9) it will print 1,2 and 4 only.
What is wrong with this code? It works on some test cases, but on most it doesn't.
c pow
1
I haven't checked your code but in the array(1,2,4,9)
the powers of 2 are1,2,4
so I don't know what your problem is. For diagnosis it's generally better to consider erroneous outputs, but you show us none of those.
– High Performance Mark
Nov 12 at 8:45
Thepow
function is a floating point function. As such it will lead to rounding problems. For powers of two, all you need are integers and bitwise shift.
– Some programmer dude
Nov 12 at 8:47
i<num+1
- for a VLA clearly defined as magnitudenum
. Um....
– WhozCraig
Nov 12 at 8:47
Oh and I suggest you do some rubber duck debugging. That last loop condition, are you sure about that one?
– Some programmer dude
Nov 12 at 8:48
1
@Someprogrammerdude last time i checked rubber ducks were out of stock. might be the reason we are seing such mediocre questions here lately.
– Swordfish
Nov 12 at 9:01
|
show 1 more comment
#include <stdio.h>
#include <math.h>
int main()
int num,i;
scanf("%d",&num);
int a[num];
for (i=0; i<num; i++)
scanf("%d",&a[i]);
for (i=0; i<num+1; i++)
if (pow(2,i) == a[i])
printf("%dn",a[i]);
I am trying to create a program that displays an integer in an array if it is a power of two. ex; an array contains the integer (1,2,4,9) it will print 1,2 and 4 only.
What is wrong with this code? It works on some test cases, but on most it doesn't.
c pow
#include <stdio.h>
#include <math.h>
int main()
int num,i;
scanf("%d",&num);
int a[num];
for (i=0; i<num; i++)
scanf("%d",&a[i]);
for (i=0; i<num+1; i++)
if (pow(2,i) == a[i])
printf("%dn",a[i]);
I am trying to create a program that displays an integer in an array if it is a power of two. ex; an array contains the integer (1,2,4,9) it will print 1,2 and 4 only.
What is wrong with this code? It works on some test cases, but on most it doesn't.
c pow
c pow
edited Nov 12 at 10:50
RishabhHardas
58113
58113
asked Nov 12 at 8:43
Aya Endo
41
41
1
I haven't checked your code but in the array(1,2,4,9)
the powers of 2 are1,2,4
so I don't know what your problem is. For diagnosis it's generally better to consider erroneous outputs, but you show us none of those.
– High Performance Mark
Nov 12 at 8:45
Thepow
function is a floating point function. As such it will lead to rounding problems. For powers of two, all you need are integers and bitwise shift.
– Some programmer dude
Nov 12 at 8:47
i<num+1
- for a VLA clearly defined as magnitudenum
. Um....
– WhozCraig
Nov 12 at 8:47
Oh and I suggest you do some rubber duck debugging. That last loop condition, are you sure about that one?
– Some programmer dude
Nov 12 at 8:48
1
@Someprogrammerdude last time i checked rubber ducks were out of stock. might be the reason we are seing such mediocre questions here lately.
– Swordfish
Nov 12 at 9:01
|
show 1 more comment
1
I haven't checked your code but in the array(1,2,4,9)
the powers of 2 are1,2,4
so I don't know what your problem is. For diagnosis it's generally better to consider erroneous outputs, but you show us none of those.
– High Performance Mark
Nov 12 at 8:45
Thepow
function is a floating point function. As such it will lead to rounding problems. For powers of two, all you need are integers and bitwise shift.
– Some programmer dude
Nov 12 at 8:47
i<num+1
- for a VLA clearly defined as magnitudenum
. Um....
– WhozCraig
Nov 12 at 8:47
Oh and I suggest you do some rubber duck debugging. That last loop condition, are you sure about that one?
– Some programmer dude
Nov 12 at 8:48
1
@Someprogrammerdude last time i checked rubber ducks were out of stock. might be the reason we are seing such mediocre questions here lately.
– Swordfish
Nov 12 at 9:01
1
1
I haven't checked your code but in the array
(1,2,4,9)
the powers of 2 are 1,2,4
so I don't know what your problem is. For diagnosis it's generally better to consider erroneous outputs, but you show us none of those.– High Performance Mark
Nov 12 at 8:45
I haven't checked your code but in the array
(1,2,4,9)
the powers of 2 are 1,2,4
so I don't know what your problem is. For diagnosis it's generally better to consider erroneous outputs, but you show us none of those.– High Performance Mark
Nov 12 at 8:45
The
pow
function is a floating point function. As such it will lead to rounding problems. For powers of two, all you need are integers and bitwise shift.– Some programmer dude
Nov 12 at 8:47
The
pow
function is a floating point function. As such it will lead to rounding problems. For powers of two, all you need are integers and bitwise shift.– Some programmer dude
Nov 12 at 8:47
i<num+1
- for a VLA clearly defined as magnitude num
. Um....– WhozCraig
Nov 12 at 8:47
i<num+1
- for a VLA clearly defined as magnitude num
. Um....– WhozCraig
Nov 12 at 8:47
Oh and I suggest you do some rubber duck debugging. That last loop condition, are you sure about that one?
– Some programmer dude
Nov 12 at 8:48
Oh and I suggest you do some rubber duck debugging. That last loop condition, are you sure about that one?
– Some programmer dude
Nov 12 at 8:48
1
1
@Someprogrammerdude last time i checked rubber ducks were out of stock. might be the reason we are seing such mediocre questions here lately.
– Swordfish
Nov 12 at 9:01
@Someprogrammerdude last time i checked rubber ducks were out of stock. might be the reason we are seing such mediocre questions here lately.
– Swordfish
Nov 12 at 9:01
|
show 1 more comment
4 Answers
4
active
oldest
votes
If value
is a power of two, only one bit is set:
#include <stdbool.h>
#include <limits.h>
bool is_pow_of_2(unsigned value)
int count = 0;
for (unsigned shift = 0; shift < sizeof(value) * CHAR_BIT; ++shift)
if (value & 1 << shift) // test if bit shift is set
++count;
if (count > 1) // if there a more than one bits set in value
return false; // it cannot be a power of 2
return true;
Plan B:
bool is_pow_of_2(signed value)
{
if(value <= 0)
return false;
// ...
this method is really nice, but can you add comments to help us understand what happens here ?
– Jean-Marc Zimmer
Nov 12 at 9:07
@Jean-MarcZimmer Added comments.
– Swordfish
Nov 12 at 9:09
Nitpick - The OP is dealing with signed numbers, whereas this solution considers only unsigned numbers. Was just wondering... what if just the sign bit is set?
– babon
Nov 12 at 9:19
@babon Have you ever seen a negative power? O.O
– Swordfish
Nov 13 at 4:45
@Swordfish What if the user wants to check with-128
or10000000
in bin?-128
is not a power of2
although just a single bit is set.2
raised to-7
doesn't give you-128
.
– babon
Nov 13 at 6:21
|
show 4 more comments
To check if a number is a power of n
with a recursive function :
function isPowOfn(int n, int number)
return (number == 1 ? TRUE : (number % n != 0 ? FALSE : isPowOfn(n, number / n)));
or (as suggested by WhozCraig)
function isPowOfn(int n, int number) (value % n == 0 && isPowOfn(n, number / n))
Input-output examples :
in: 2, 6
processing: 3
out: FALSE
in: 2, 16
processing: 8 - 4 - 2 - 1
out: TRUE
in: 2, 162
processing: 81
out: FALSE
in: 3, 81
processing: 27 - 9 - 3 - 1
out: TRUE
in: 5, 244140625
processing: 48828125 - 9765625 - 1953125 - 390625 - 78125 - 15625 - 3125 - 625 - 125 - 25 - 5 - 1
out: TRUE
in: 4, 67957741992
processing: 16989435498
out: FALSE
Just realized that. I wanted to use a function to avoid double-ternary. Fixed
– Jean-Marc Zimmer
Nov 12 at 9:14
You can anyway.
– WhozCraig
Nov 12 at 9:14
1
Single line:return value == 1 || (value % n == 0 && isPowOfn(n,value / n));
– WhozCraig
Nov 12 at 9:16
add a comment |
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
Explanation: A power of 2 has only 1 bit set. If we subtract 1 from a power of 2 then all unset bits after the only set bit become set; and the set bit becomes unset.
If x
is a power of 2, x&(x-1)
will be 0. (!(x&(x-1)))
will be 1. And the return expression will be 1.
The logical AND (&&
) of this expression with x
is to ensure that this will not be true if x
is 0.
add a comment |
The other methods proposed to test if a number is a power of two make assumptions about the representation of numbers. This should be avoided. Always write generic code that is easy to understand and works everywhere. Avoid recursion too if possible.
Too many programmers try to be clever. You should consider other methods only if this function is a bottleneck in your program and if your compiler is not smart enough. As a beginner you are obviously not in that situation.
bool is_power_of_2 (int n)
if (n < 1)
return false;
while (n % 2 == 0)
n = n / 2;
return (n == 1);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53258482%2fc-program-to-display-the-number-if-it-is-a-power-of-2-in-an-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
If value
is a power of two, only one bit is set:
#include <stdbool.h>
#include <limits.h>
bool is_pow_of_2(unsigned value)
int count = 0;
for (unsigned shift = 0; shift < sizeof(value) * CHAR_BIT; ++shift)
if (value & 1 << shift) // test if bit shift is set
++count;
if (count > 1) // if there a more than one bits set in value
return false; // it cannot be a power of 2
return true;
Plan B:
bool is_pow_of_2(signed value)
{
if(value <= 0)
return false;
// ...
this method is really nice, but can you add comments to help us understand what happens here ?
– Jean-Marc Zimmer
Nov 12 at 9:07
@Jean-MarcZimmer Added comments.
– Swordfish
Nov 12 at 9:09
Nitpick - The OP is dealing with signed numbers, whereas this solution considers only unsigned numbers. Was just wondering... what if just the sign bit is set?
– babon
Nov 12 at 9:19
@babon Have you ever seen a negative power? O.O
– Swordfish
Nov 13 at 4:45
@Swordfish What if the user wants to check with-128
or10000000
in bin?-128
is not a power of2
although just a single bit is set.2
raised to-7
doesn't give you-128
.
– babon
Nov 13 at 6:21
|
show 4 more comments
If value
is a power of two, only one bit is set:
#include <stdbool.h>
#include <limits.h>
bool is_pow_of_2(unsigned value)
int count = 0;
for (unsigned shift = 0; shift < sizeof(value) * CHAR_BIT; ++shift)
if (value & 1 << shift) // test if bit shift is set
++count;
if (count > 1) // if there a more than one bits set in value
return false; // it cannot be a power of 2
return true;
Plan B:
bool is_pow_of_2(signed value)
{
if(value <= 0)
return false;
// ...
this method is really nice, but can you add comments to help us understand what happens here ?
– Jean-Marc Zimmer
Nov 12 at 9:07
@Jean-MarcZimmer Added comments.
– Swordfish
Nov 12 at 9:09
Nitpick - The OP is dealing with signed numbers, whereas this solution considers only unsigned numbers. Was just wondering... what if just the sign bit is set?
– babon
Nov 12 at 9:19
@babon Have you ever seen a negative power? O.O
– Swordfish
Nov 13 at 4:45
@Swordfish What if the user wants to check with-128
or10000000
in bin?-128
is not a power of2
although just a single bit is set.2
raised to-7
doesn't give you-128
.
– babon
Nov 13 at 6:21
|
show 4 more comments
If value
is a power of two, only one bit is set:
#include <stdbool.h>
#include <limits.h>
bool is_pow_of_2(unsigned value)
int count = 0;
for (unsigned shift = 0; shift < sizeof(value) * CHAR_BIT; ++shift)
if (value & 1 << shift) // test if bit shift is set
++count;
if (count > 1) // if there a more than one bits set in value
return false; // it cannot be a power of 2
return true;
Plan B:
bool is_pow_of_2(signed value)
{
if(value <= 0)
return false;
// ...
If value
is a power of two, only one bit is set:
#include <stdbool.h>
#include <limits.h>
bool is_pow_of_2(unsigned value)
int count = 0;
for (unsigned shift = 0; shift < sizeof(value) * CHAR_BIT; ++shift)
if (value & 1 << shift) // test if bit shift is set
++count;
if (count > 1) // if there a more than one bits set in value
return false; // it cannot be a power of 2
return true;
Plan B:
bool is_pow_of_2(signed value)
{
if(value <= 0)
return false;
// ...
edited Nov 13 at 6:46
answered Nov 12 at 8:54
Swordfish
1
1
this method is really nice, but can you add comments to help us understand what happens here ?
– Jean-Marc Zimmer
Nov 12 at 9:07
@Jean-MarcZimmer Added comments.
– Swordfish
Nov 12 at 9:09
Nitpick - The OP is dealing with signed numbers, whereas this solution considers only unsigned numbers. Was just wondering... what if just the sign bit is set?
– babon
Nov 12 at 9:19
@babon Have you ever seen a negative power? O.O
– Swordfish
Nov 13 at 4:45
@Swordfish What if the user wants to check with-128
or10000000
in bin?-128
is not a power of2
although just a single bit is set.2
raised to-7
doesn't give you-128
.
– babon
Nov 13 at 6:21
|
show 4 more comments
this method is really nice, but can you add comments to help us understand what happens here ?
– Jean-Marc Zimmer
Nov 12 at 9:07
@Jean-MarcZimmer Added comments.
– Swordfish
Nov 12 at 9:09
Nitpick - The OP is dealing with signed numbers, whereas this solution considers only unsigned numbers. Was just wondering... what if just the sign bit is set?
– babon
Nov 12 at 9:19
@babon Have you ever seen a negative power? O.O
– Swordfish
Nov 13 at 4:45
@Swordfish What if the user wants to check with-128
or10000000
in bin?-128
is not a power of2
although just a single bit is set.2
raised to-7
doesn't give you-128
.
– babon
Nov 13 at 6:21
this method is really nice, but can you add comments to help us understand what happens here ?
– Jean-Marc Zimmer
Nov 12 at 9:07
this method is really nice, but can you add comments to help us understand what happens here ?
– Jean-Marc Zimmer
Nov 12 at 9:07
@Jean-MarcZimmer Added comments.
– Swordfish
Nov 12 at 9:09
@Jean-MarcZimmer Added comments.
– Swordfish
Nov 12 at 9:09
Nitpick - The OP is dealing with signed numbers, whereas this solution considers only unsigned numbers. Was just wondering... what if just the sign bit is set?
– babon
Nov 12 at 9:19
Nitpick - The OP is dealing with signed numbers, whereas this solution considers only unsigned numbers. Was just wondering... what if just the sign bit is set?
– babon
Nov 12 at 9:19
@babon Have you ever seen a negative power? O.O
– Swordfish
Nov 13 at 4:45
@babon Have you ever seen a negative power? O.O
– Swordfish
Nov 13 at 4:45
@Swordfish What if the user wants to check with
-128
or 10000000
in bin? -128
is not a power of 2
although just a single bit is set. 2
raised to -7
doesn't give you -128
.– babon
Nov 13 at 6:21
@Swordfish What if the user wants to check with
-128
or 10000000
in bin? -128
is not a power of 2
although just a single bit is set. 2
raised to -7
doesn't give you -128
.– babon
Nov 13 at 6:21
|
show 4 more comments
To check if a number is a power of n
with a recursive function :
function isPowOfn(int n, int number)
return (number == 1 ? TRUE : (number % n != 0 ? FALSE : isPowOfn(n, number / n)));
or (as suggested by WhozCraig)
function isPowOfn(int n, int number) (value % n == 0 && isPowOfn(n, number / n))
Input-output examples :
in: 2, 6
processing: 3
out: FALSE
in: 2, 16
processing: 8 - 4 - 2 - 1
out: TRUE
in: 2, 162
processing: 81
out: FALSE
in: 3, 81
processing: 27 - 9 - 3 - 1
out: TRUE
in: 5, 244140625
processing: 48828125 - 9765625 - 1953125 - 390625 - 78125 - 15625 - 3125 - 625 - 125 - 25 - 5 - 1
out: TRUE
in: 4, 67957741992
processing: 16989435498
out: FALSE
Just realized that. I wanted to use a function to avoid double-ternary. Fixed
– Jean-Marc Zimmer
Nov 12 at 9:14
You can anyway.
– WhozCraig
Nov 12 at 9:14
1
Single line:return value == 1 || (value % n == 0 && isPowOfn(n,value / n));
– WhozCraig
Nov 12 at 9:16
add a comment |
To check if a number is a power of n
with a recursive function :
function isPowOfn(int n, int number)
return (number == 1 ? TRUE : (number % n != 0 ? FALSE : isPowOfn(n, number / n)));
or (as suggested by WhozCraig)
function isPowOfn(int n, int number) (value % n == 0 && isPowOfn(n, number / n))
Input-output examples :
in: 2, 6
processing: 3
out: FALSE
in: 2, 16
processing: 8 - 4 - 2 - 1
out: TRUE
in: 2, 162
processing: 81
out: FALSE
in: 3, 81
processing: 27 - 9 - 3 - 1
out: TRUE
in: 5, 244140625
processing: 48828125 - 9765625 - 1953125 - 390625 - 78125 - 15625 - 3125 - 625 - 125 - 25 - 5 - 1
out: TRUE
in: 4, 67957741992
processing: 16989435498
out: FALSE
Just realized that. I wanted to use a function to avoid double-ternary. Fixed
– Jean-Marc Zimmer
Nov 12 at 9:14
You can anyway.
– WhozCraig
Nov 12 at 9:14
1
Single line:return value == 1 || (value % n == 0 && isPowOfn(n,value / n));
– WhozCraig
Nov 12 at 9:16
add a comment |
To check if a number is a power of n
with a recursive function :
function isPowOfn(int n, int number)
return (number == 1 ? TRUE : (number % n != 0 ? FALSE : isPowOfn(n, number / n)));
or (as suggested by WhozCraig)
function isPowOfn(int n, int number) (value % n == 0 && isPowOfn(n, number / n))
Input-output examples :
in: 2, 6
processing: 3
out: FALSE
in: 2, 16
processing: 8 - 4 - 2 - 1
out: TRUE
in: 2, 162
processing: 81
out: FALSE
in: 3, 81
processing: 27 - 9 - 3 - 1
out: TRUE
in: 5, 244140625
processing: 48828125 - 9765625 - 1953125 - 390625 - 78125 - 15625 - 3125 - 625 - 125 - 25 - 5 - 1
out: TRUE
in: 4, 67957741992
processing: 16989435498
out: FALSE
To check if a number is a power of n
with a recursive function :
function isPowOfn(int n, int number)
return (number == 1 ? TRUE : (number % n != 0 ? FALSE : isPowOfn(n, number / n)));
or (as suggested by WhozCraig)
function isPowOfn(int n, int number) (value % n == 0 && isPowOfn(n, number / n))
Input-output examples :
in: 2, 6
processing: 3
out: FALSE
in: 2, 16
processing: 8 - 4 - 2 - 1
out: TRUE
in: 2, 162
processing: 81
out: FALSE
in: 3, 81
processing: 27 - 9 - 3 - 1
out: TRUE
in: 5, 244140625
processing: 48828125 - 9765625 - 1953125 - 390625 - 78125 - 15625 - 3125 - 625 - 125 - 25 - 5 - 1
out: TRUE
in: 4, 67957741992
processing: 16989435498
out: FALSE
edited Nov 12 at 9:22
answered Nov 12 at 9:04
Jean-Marc Zimmer
37414
37414
Just realized that. I wanted to use a function to avoid double-ternary. Fixed
– Jean-Marc Zimmer
Nov 12 at 9:14
You can anyway.
– WhozCraig
Nov 12 at 9:14
1
Single line:return value == 1 || (value % n == 0 && isPowOfn(n,value / n));
– WhozCraig
Nov 12 at 9:16
add a comment |
Just realized that. I wanted to use a function to avoid double-ternary. Fixed
– Jean-Marc Zimmer
Nov 12 at 9:14
You can anyway.
– WhozCraig
Nov 12 at 9:14
1
Single line:return value == 1 || (value % n == 0 && isPowOfn(n,value / n));
– WhozCraig
Nov 12 at 9:16
Just realized that. I wanted to use a function to avoid double-ternary. Fixed
– Jean-Marc Zimmer
Nov 12 at 9:14
Just realized that. I wanted to use a function to avoid double-ternary. Fixed
– Jean-Marc Zimmer
Nov 12 at 9:14
You can anyway.
– WhozCraig
Nov 12 at 9:14
You can anyway.
– WhozCraig
Nov 12 at 9:14
1
1
Single line:
return value == 1 || (value % n == 0 && isPowOfn(n,value / n));
– WhozCraig
Nov 12 at 9:16
Single line:
return value == 1 || (value % n == 0 && isPowOfn(n,value / n));
– WhozCraig
Nov 12 at 9:16
add a comment |
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
Explanation: A power of 2 has only 1 bit set. If we subtract 1 from a power of 2 then all unset bits after the only set bit become set; and the set bit becomes unset.
If x
is a power of 2, x&(x-1)
will be 0. (!(x&(x-1)))
will be 1. And the return expression will be 1.
The logical AND (&&
) of this expression with x
is to ensure that this will not be true if x
is 0.
add a comment |
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
Explanation: A power of 2 has only 1 bit set. If we subtract 1 from a power of 2 then all unset bits after the only set bit become set; and the set bit becomes unset.
If x
is a power of 2, x&(x-1)
will be 0. (!(x&(x-1)))
will be 1. And the return expression will be 1.
The logical AND (&&
) of this expression with x
is to ensure that this will not be true if x
is 0.
add a comment |
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
Explanation: A power of 2 has only 1 bit set. If we subtract 1 from a power of 2 then all unset bits after the only set bit become set; and the set bit becomes unset.
If x
is a power of 2, x&(x-1)
will be 0. (!(x&(x-1)))
will be 1. And the return expression will be 1.
The logical AND (&&
) of this expression with x
is to ensure that this will not be true if x
is 0.
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
/* First x in the below expression is for the case when x is 0 */
return x && (!(x&(x-1)));
Explanation: A power of 2 has only 1 bit set. If we subtract 1 from a power of 2 then all unset bits after the only set bit become set; and the set bit becomes unset.
If x
is a power of 2, x&(x-1)
will be 0. (!(x&(x-1)))
will be 1. And the return expression will be 1.
The logical AND (&&
) of this expression with x
is to ensure that this will not be true if x
is 0.
edited Nov 12 at 10:14
answered Nov 12 at 9:34
P.W
10.9k3742
10.9k3742
add a comment |
add a comment |
The other methods proposed to test if a number is a power of two make assumptions about the representation of numbers. This should be avoided. Always write generic code that is easy to understand and works everywhere. Avoid recursion too if possible.
Too many programmers try to be clever. You should consider other methods only if this function is a bottleneck in your program and if your compiler is not smart enough. As a beginner you are obviously not in that situation.
bool is_power_of_2 (int n)
if (n < 1)
return false;
while (n % 2 == 0)
n = n / 2;
return (n == 1);
add a comment |
The other methods proposed to test if a number is a power of two make assumptions about the representation of numbers. This should be avoided. Always write generic code that is easy to understand and works everywhere. Avoid recursion too if possible.
Too many programmers try to be clever. You should consider other methods only if this function is a bottleneck in your program and if your compiler is not smart enough. As a beginner you are obviously not in that situation.
bool is_power_of_2 (int n)
if (n < 1)
return false;
while (n % 2 == 0)
n = n / 2;
return (n == 1);
add a comment |
The other methods proposed to test if a number is a power of two make assumptions about the representation of numbers. This should be avoided. Always write generic code that is easy to understand and works everywhere. Avoid recursion too if possible.
Too many programmers try to be clever. You should consider other methods only if this function is a bottleneck in your program and if your compiler is not smart enough. As a beginner you are obviously not in that situation.
bool is_power_of_2 (int n)
if (n < 1)
return false;
while (n % 2 == 0)
n = n / 2;
return (n == 1);
The other methods proposed to test if a number is a power of two make assumptions about the representation of numbers. This should be avoided. Always write generic code that is easy to understand and works everywhere. Avoid recursion too if possible.
Too many programmers try to be clever. You should consider other methods only if this function is a bottleneck in your program and if your compiler is not smart enough. As a beginner you are obviously not in that situation.
bool is_power_of_2 (int n)
if (n < 1)
return false;
while (n % 2 == 0)
n = n / 2;
return (n == 1);
answered Nov 12 at 10:26
Antoine Mathys
5,7371431
5,7371431
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53258482%2fc-program-to-display-the-number-if-it-is-a-power-of-2-in-an-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
I haven't checked your code but in the array
(1,2,4,9)
the powers of 2 are1,2,4
so I don't know what your problem is. For diagnosis it's generally better to consider erroneous outputs, but you show us none of those.– High Performance Mark
Nov 12 at 8:45
The
pow
function is a floating point function. As such it will lead to rounding problems. For powers of two, all you need are integers and bitwise shift.– Some programmer dude
Nov 12 at 8:47
i<num+1
- for a VLA clearly defined as magnitudenum
. Um....– WhozCraig
Nov 12 at 8:47
Oh and I suggest you do some rubber duck debugging. That last loop condition, are you sure about that one?
– Some programmer dude
Nov 12 at 8:48
1
@Someprogrammerdude last time i checked rubber ducks were out of stock. might be the reason we are seing such mediocre questions here lately.
– Swordfish
Nov 12 at 9:01