Checking if a number is a power of 2 without loops

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
4
down vote

favorite












I made a short program which checks if a number is a power of 2 without using any loops.
The idea: A number which is a power of 2 must have only one bit "1" ( ex: 8= 1000, 4=100 and so on).
Suppose we have a power of 2:nr = 10...000 (in binary), if we subtract 1 we will get something like this:nr-1= 01...111. Now, if we do nr&(nr-1) we should always get 0 if the nr is a power of 2 and some random number if it isn't. What other solutions are there for this problem?



#include <stdio.h>
#include <stdlib.h>

int main()

int nr;
scanf("%d",&nr);
if((nr&(nr-1))==0)

printf("n%d is a power of 2",nr);

else

printf("n%d is not a power of 2",nr);

return 0;







share|improve this question



















  • but i'm not checking if a number is divisible by 2, i'm checking if a number is a power of 2. what do you mean?
    – sneakysnake
    May 14 at 22:00










  • CPUs have a "population count" instruction built in. Compilers often provide access to it via an intrinsic. So return ++popcnt(nr)==1; is all you need.
    – JDługosz
    May 15 at 2:12










  • For related bit-fiddling tricks, see the book "Hacker's Delight".
    – Roland Illig
    May 15 at 4:45

















up vote
4
down vote

favorite












I made a short program which checks if a number is a power of 2 without using any loops.
The idea: A number which is a power of 2 must have only one bit "1" ( ex: 8= 1000, 4=100 and so on).
Suppose we have a power of 2:nr = 10...000 (in binary), if we subtract 1 we will get something like this:nr-1= 01...111. Now, if we do nr&(nr-1) we should always get 0 if the nr is a power of 2 and some random number if it isn't. What other solutions are there for this problem?



#include <stdio.h>
#include <stdlib.h>

int main()

int nr;
scanf("%d",&nr);
if((nr&(nr-1))==0)

printf("n%d is a power of 2",nr);

else

printf("n%d is not a power of 2",nr);

return 0;







share|improve this question



















  • but i'm not checking if a number is divisible by 2, i'm checking if a number is a power of 2. what do you mean?
    – sneakysnake
    May 14 at 22:00










  • CPUs have a "population count" instruction built in. Compilers often provide access to it via an intrinsic. So return ++popcnt(nr)==1; is all you need.
    – JDługosz
    May 15 at 2:12










  • For related bit-fiddling tricks, see the book "Hacker's Delight".
    – Roland Illig
    May 15 at 4:45













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I made a short program which checks if a number is a power of 2 without using any loops.
The idea: A number which is a power of 2 must have only one bit "1" ( ex: 8= 1000, 4=100 and so on).
Suppose we have a power of 2:nr = 10...000 (in binary), if we subtract 1 we will get something like this:nr-1= 01...111. Now, if we do nr&(nr-1) we should always get 0 if the nr is a power of 2 and some random number if it isn't. What other solutions are there for this problem?



#include <stdio.h>
#include <stdlib.h>

int main()

int nr;
scanf("%d",&nr);
if((nr&(nr-1))==0)

printf("n%d is a power of 2",nr);

else

printf("n%d is not a power of 2",nr);

return 0;







share|improve this question











I made a short program which checks if a number is a power of 2 without using any loops.
The idea: A number which is a power of 2 must have only one bit "1" ( ex: 8= 1000, 4=100 and so on).
Suppose we have a power of 2:nr = 10...000 (in binary), if we subtract 1 we will get something like this:nr-1= 01...111. Now, if we do nr&(nr-1) we should always get 0 if the nr is a power of 2 and some random number if it isn't. What other solutions are there for this problem?



#include <stdio.h>
#include <stdlib.h>

int main()

int nr;
scanf("%d",&nr);
if((nr&(nr-1))==0)

printf("n%d is a power of 2",nr);

else

printf("n%d is not a power of 2",nr);

return 0;









share|improve this question










share|improve this question




share|improve this question









asked May 14 at 21:47









sneakysnake

635




635











  • but i'm not checking if a number is divisible by 2, i'm checking if a number is a power of 2. what do you mean?
    – sneakysnake
    May 14 at 22:00










  • CPUs have a "population count" instruction built in. Compilers often provide access to it via an intrinsic. So return ++popcnt(nr)==1; is all you need.
    – JDługosz
    May 15 at 2:12










  • For related bit-fiddling tricks, see the book "Hacker's Delight".
    – Roland Illig
    May 15 at 4:45

















  • but i'm not checking if a number is divisible by 2, i'm checking if a number is a power of 2. what do you mean?
    – sneakysnake
    May 14 at 22:00










  • CPUs have a "population count" instruction built in. Compilers often provide access to it via an intrinsic. So return ++popcnt(nr)==1; is all you need.
    – JDługosz
    May 15 at 2:12










  • For related bit-fiddling tricks, see the book "Hacker's Delight".
    – Roland Illig
    May 15 at 4:45
















but i'm not checking if a number is divisible by 2, i'm checking if a number is a power of 2. what do you mean?
– sneakysnake
May 14 at 22:00




but i'm not checking if a number is divisible by 2, i'm checking if a number is a power of 2. what do you mean?
– sneakysnake
May 14 at 22:00












CPUs have a "population count" instruction built in. Compilers often provide access to it via an intrinsic. So return ++popcnt(nr)==1; is all you need.
– JDługosz
May 15 at 2:12




CPUs have a "population count" instruction built in. Compilers often provide access to it via an intrinsic. So return ++popcnt(nr)==1; is all you need.
– JDługosz
May 15 at 2:12












For related bit-fiddling tricks, see the book "Hacker's Delight".
– Roland Illig
May 15 at 4:45





For related bit-fiddling tricks, see the book "Hacker's Delight".
– Roland Illig
May 15 at 4:45











2 Answers
2






active

oldest

votes

















up vote
3
down vote



accepted











What other solutions are there for this problem?




OP's code can incorrectly reports 0 and -2147483648 (INT_MIN) are both powers-of 2.



A simple change is to use unsigned rather than int @Toby Speight. This avoids 1) the corner case of INT_MIN - 1 which is undefined behavior and 2) and-ing a negative int, which is implementation defined behavior.



unsigned nr;
scanf("%u",&nr);
if ((nr & (nr-1)) == 0 && nr)





share|improve this answer






























    up vote
    10
    down vote













    • Use only necessary #includes. The <stdlib.h> is not needed here.


    • Give your operators some breathing space. ((nr&(nr-1))==0) is next to unreadable.



    • Separate logic from presentation:



      int is_power_of_two(int nr)

      return nr & (nr - 1) == 0;



      is much more reusable.



    • Care about corner cases. Your code claims that 0 is a power of two (which it is not).






    share|improve this answer

















    • 2




      Probably ought to add a few negative numbers to the test suite of corner cases - or (better) change nr to an unsigned type.
      – Toby Speight
      May 15 at 10:25










    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    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: "196"
    ;
    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',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194401%2fchecking-if-a-number-is-a-power-of-2-without-loops%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote



    accepted











    What other solutions are there for this problem?




    OP's code can incorrectly reports 0 and -2147483648 (INT_MIN) are both powers-of 2.



    A simple change is to use unsigned rather than int @Toby Speight. This avoids 1) the corner case of INT_MIN - 1 which is undefined behavior and 2) and-ing a negative int, which is implementation defined behavior.



    unsigned nr;
    scanf("%u",&nr);
    if ((nr & (nr-1)) == 0 && nr)





    share|improve this answer



























      up vote
      3
      down vote



      accepted











      What other solutions are there for this problem?




      OP's code can incorrectly reports 0 and -2147483648 (INT_MIN) are both powers-of 2.



      A simple change is to use unsigned rather than int @Toby Speight. This avoids 1) the corner case of INT_MIN - 1 which is undefined behavior and 2) and-ing a negative int, which is implementation defined behavior.



      unsigned nr;
      scanf("%u",&nr);
      if ((nr & (nr-1)) == 0 && nr)





      share|improve this answer

























        up vote
        3
        down vote



        accepted







        up vote
        3
        down vote



        accepted







        What other solutions are there for this problem?




        OP's code can incorrectly reports 0 and -2147483648 (INT_MIN) are both powers-of 2.



        A simple change is to use unsigned rather than int @Toby Speight. This avoids 1) the corner case of INT_MIN - 1 which is undefined behavior and 2) and-ing a negative int, which is implementation defined behavior.



        unsigned nr;
        scanf("%u",&nr);
        if ((nr & (nr-1)) == 0 && nr)





        share|improve this answer
















        What other solutions are there for this problem?




        OP's code can incorrectly reports 0 and -2147483648 (INT_MIN) are both powers-of 2.



        A simple change is to use unsigned rather than int @Toby Speight. This avoids 1) the corner case of INT_MIN - 1 which is undefined behavior and 2) and-ing a negative int, which is implementation defined behavior.



        unsigned nr;
        scanf("%u",&nr);
        if ((nr & (nr-1)) == 0 && nr)






        share|improve this answer















        share|improve this answer



        share|improve this answer








        edited May 15 at 15:40


























        answered May 15 at 15:32









        chux

        11.4k11238




        11.4k11238






















            up vote
            10
            down vote













            • Use only necessary #includes. The <stdlib.h> is not needed here.


            • Give your operators some breathing space. ((nr&(nr-1))==0) is next to unreadable.



            • Separate logic from presentation:



              int is_power_of_two(int nr)

              return nr & (nr - 1) == 0;



              is much more reusable.



            • Care about corner cases. Your code claims that 0 is a power of two (which it is not).






            share|improve this answer

















            • 2




              Probably ought to add a few negative numbers to the test suite of corner cases - or (better) change nr to an unsigned type.
              – Toby Speight
              May 15 at 10:25














            up vote
            10
            down vote













            • Use only necessary #includes. The <stdlib.h> is not needed here.


            • Give your operators some breathing space. ((nr&(nr-1))==0) is next to unreadable.



            • Separate logic from presentation:



              int is_power_of_two(int nr)

              return nr & (nr - 1) == 0;



              is much more reusable.



            • Care about corner cases. Your code claims that 0 is a power of two (which it is not).






            share|improve this answer

















            • 2




              Probably ought to add a few negative numbers to the test suite of corner cases - or (better) change nr to an unsigned type.
              – Toby Speight
              May 15 at 10:25












            up vote
            10
            down vote










            up vote
            10
            down vote









            • Use only necessary #includes. The <stdlib.h> is not needed here.


            • Give your operators some breathing space. ((nr&(nr-1))==0) is next to unreadable.



            • Separate logic from presentation:



              int is_power_of_two(int nr)

              return nr & (nr - 1) == 0;



              is much more reusable.



            • Care about corner cases. Your code claims that 0 is a power of two (which it is not).






            share|improve this answer













            • Use only necessary #includes. The <stdlib.h> is not needed here.


            • Give your operators some breathing space. ((nr&(nr-1))==0) is next to unreadable.



            • Separate logic from presentation:



              int is_power_of_two(int nr)

              return nr & (nr - 1) == 0;



              is much more reusable.



            • Care about corner cases. Your code claims that 0 is a power of two (which it is not).







            share|improve this answer













            share|improve this answer



            share|improve this answer











            answered May 14 at 22:10









            vnp

            36.4k12890




            36.4k12890







            • 2




              Probably ought to add a few negative numbers to the test suite of corner cases - or (better) change nr to an unsigned type.
              – Toby Speight
              May 15 at 10:25












            • 2




              Probably ought to add a few negative numbers to the test suite of corner cases - or (better) change nr to an unsigned type.
              – Toby Speight
              May 15 at 10:25







            2




            2




            Probably ought to add a few negative numbers to the test suite of corner cases - or (better) change nr to an unsigned type.
            – Toby Speight
            May 15 at 10:25




            Probably ought to add a few negative numbers to the test suite of corner cases - or (better) change nr to an unsigned type.
            – Toby Speight
            May 15 at 10:25












             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194401%2fchecking-if-a-number-is-a-power-of-2-without-loops%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Python Lists

            Aion

            JavaScript Array Iteration Methods