Re: algorithm to identify number from 0-16384 having at most 4 1s in its binary number



Ujjaval wrote:
> Hey all,
>
> I want to get the numbers from 0-16384 whose equivalent binary number
> has at the most 4 1s in it.
>
> I can do this by setting up a counter and doing an AND operation of a
> number with all numbers which are power of 2 between 0-16384. I update
> the couter for each successful AND operation and at the end check
> whether the counter is <= 4 or not.
>
> Is there any more efficient way to do this??

Sure, use Python:

>>> import gmpy
>>> for n in xrange(16385):
if gmpy.popcount(n)<=4: print n,


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
32 33 34 35 36 37 38 39 40 41 42 43 ...

Note, 31 skipped because it has 5 binary 1s.

.... 15360 16384

And all numbers between 15360 and 16384 have >4 binary 1s.


>
> Thanks,
> Ujjaval

.



Relevant Pages

  • Re: GoTo in Java
    ... Hey, that Python stuff is pretty readable. ... Frank ... Prev by Date: ...
    (comp.lang.cobol)
  • Re: Problem with printing input.
    ... >> hey you rama krishna ... Prev by Date: ...
    (comp.lang.c)
  • Re: Why we will use obj$func() often
    ... >to Prothon-users. ... Oh, no problem, there's some Python content (see below for some comments ... defined which take the class as their first parameter just like a normal ... call and saying "hey, that's a class, that can't be the first parameter ...
    (comp.lang.python)
  • Re: Error when openeing word
    ... > Please respond in the newsgroups so everyone can follow along. ... >> Hey all, ... >> MYOB has been installed on this system, can anyone help me with this? ... Prev by Date: ...
    (microsoft.public.word.application.errors)
  • Re: SUMIF - 2 conditions - with references
    ... > hey thanks for your help, i converted both columns to numbers but it ... > one condition the other condition is a date, so maybe that is affecting ... > vect98's Profile: ... Prev by Date: ...
    (microsoft.public.excel.worksheet.functions)