Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Algorithms
  4. Algorithm to count how many "1" in binary o(1)

Algorithm to count how many "1" in binary o(1)

Scheduled Pinned Locked Moved Algorithms
questionalgorithmstutorial
9 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U Offline
    U Offline
    User 11020890
    wrote on last edited by
    #1

    for example: 9 = 1001 in binary so the function GetNumOfBinary(9) = 2. I know I can do it in o(n) (time) by convert it to binary and exam digit by digit. I've been told I can do it using space as much as I need. How can I do it? (it's seems impossible because I need to check every digit, doesn't matter which way I do it and it'll be still o(n))

    Kornfeld Eliyahu PeterK Richard DeemingR A J L 5 Replies Last reply
    0
    • U User 11020890

      for example: 9 = 1001 in binary so the function GetNumOfBinary(9) = 2. I know I can do it in o(n) (time) by convert it to binary and exam digit by digit. I've been told I can do it using space as much as I need. How can I do it? (it's seems impossible because I need to check every digit, doesn't matter which way I do it and it'll be still o(n))

      Kornfeld Eliyahu PeterK Offline
      Kornfeld Eliyahu PeterK Offline
      Kornfeld Eliyahu Peter
      wrote on last edited by
      #2

      Read this - http://en.wikipedia.org/wiki/Hamming_weight[^]

      I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V) תפסיק לספר לה' כמה הצרות שלך גדולות, תספר לצרות שלך כמה ה' גדול!

      "It never ceases to amaze me that a spacecraft launched in 1977 can be fixed remotely from Earth." ― Brian Cox

      U 1 Reply Last reply
      0
      • U User 11020890

        for example: 9 = 1001 in binary so the function GetNumOfBinary(9) = 2. I know I can do it in o(n) (time) by convert it to binary and exam digit by digit. I've been told I can do it using space as much as I need. How can I do it? (it's seems impossible because I need to check every digit, doesn't matter which way I do it and it'll be still o(n))

        Richard DeemingR Offline
        Richard DeemingR Offline
        Richard Deeming
        wrote on last edited by
        #3

        There are several algorithms listed here[^]. For a 32-bit integer, you probably want "Counting bits set, in parallel[^]":

        int CountBitsSet(int v)
        {
        v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
        v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
        return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
        }

        Just don't ask me to explain how it works! :-O


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

        Kornfeld Eliyahu PeterK L 2 Replies Last reply
        0
        • Richard DeemingR Richard Deeming

          There are several algorithms listed here[^]. For a 32-bit integer, you probably want "Counting bits set, in parallel[^]":

          int CountBitsSet(int v)
          {
          v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
          v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
          return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
          }

          Just don't ask me to explain how it works! :-O


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          Kornfeld Eliyahu PeterK Offline
          Kornfeld Eliyahu PeterK Offline
          Kornfeld Eliyahu Peter
          wrote on last edited by
          #4

          Richard Deeming wrote:

          Just don't ask me to explain how it works!

          How, how indeed...http://en.wikipedia.org/wiki/Hamming_weight[^]

          I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V) תפסיק לספר לה' כמה הצרות שלך גדולות, תספר לצרות שלך כמה ה' גדול!

          "It never ceases to amaze me that a spacecraft launched in 1977 can be fixed remotely from Earth." ― Brian Cox

          1 Reply Last reply
          0
          • U User 11020890

            for example: 9 = 1001 in binary so the function GetNumOfBinary(9) = 2. I know I can do it in o(n) (time) by convert it to binary and exam digit by digit. I've been told I can do it using space as much as I need. How can I do it? (it's seems impossible because I need to check every digit, doesn't matter which way I do it and it'll be still o(n))

            A Offline
            A Offline
            Aurimas
            wrote on last edited by
            #5

            if you're using c++ gcc - __builtin_popcount

            1 Reply Last reply
            0
            • Kornfeld Eliyahu PeterK Kornfeld Eliyahu Peter

              Read this - http://en.wikipedia.org/wiki/Hamming_weight[^]

              I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V) תפסיק לספר לה' כמה הצרות שלך גדולות, תספר לצרות שלך כמה ה' גדול!

              U Offline
              U Offline
              User 11020890
              wrote on last edited by
              #6

              Thank you for the answer. This is the answer I was looking for. Thank for the other for the answers.

              1 Reply Last reply
              0
              • U User 11020890

                for example: 9 = 1001 in binary so the function GetNumOfBinary(9) = 2. I know I can do it in o(n) (time) by convert it to binary and exam digit by digit. I've been told I can do it using space as much as I need. How can I do it? (it's seems impossible because I need to check every digit, doesn't matter which way I do it and it'll be still o(n))

                J Offline
                J Offline
                Joe DiNatale
                wrote on last edited by
                #7

                Member 11055093 wrote:

                I've been told I can do it using space as much as I need.

                Fastest way with unlimited space would be a lookup table.

                1 Reply Last reply
                0
                • Richard DeemingR Richard Deeming

                  There are several algorithms listed here[^]. For a 32-bit integer, you probably want "Counting bits set, in parallel[^]":

                  int CountBitsSet(int v)
                  {
                  v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
                  v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
                  return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
                  }

                  Just don't ask me to explain how it works! :-O


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  It first sums pairs of adjacent bits, then it sums the groups of 2, then the same thing with the nibbles, and finally it cheats and sums the bytes with a multiplication.

                  1 Reply Last reply
                  0
                  • U User 11020890

                    for example: 9 = 1001 in binary so the function GetNumOfBinary(9) = 2. I know I can do it in o(n) (time) by convert it to binary and exam digit by digit. I've been told I can do it using space as much as I need. How can I do it? (it's seems impossible because I need to check every digit, doesn't matter which way I do it and it'll be still o(n))

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #9

                    It depends on your abstract model. With the usual model, you can't do any better than O(n) (so o(n) is not happening, or did you write a lower case o by accident?) - obviously on a plain old Turing machine, you're going to have to read every bit. But this problem is in NC. You could sum n/2 pairs of bits, then n/4 pairs of "2bit numbers", n/8 pairs of nibbles, etc, and you're done in log n steps, with each step taking logarithmic time too (adders) (sometimes not counted), all with a polynomial number of processing elements. Similarly in "broadword computing", you would say that you could compute this in O(log n) broadword steps - using the same construction, but now every layer is a couple of steps (mask and add) (with the addition counted as 1 step, instead of as a circuit of depth O(log n)) Practically, on 32bit words but "pretending 32 is not a constant", you can still use the same construction for an O(log n) algorithm possibly with a multiplication trick to do several sums at once (already shown in answers) or lookup tables or (with as much space as you need, you could cheat terribly and compute any mapping from 32bit integers to anything in a single step), if available, the popcnt instruction. For arrays you could use a pshufb-based trick[^] (pshufb is awesome).

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups