count ones in range

20

1

Challenge :

Count the number of ones 1 in the binary representation of all number between a range.


Input :

Two non-decimal positive integers


Output :

The sum of all the 1s in the range between the two numbers.


Example :

4 , 7        ---> 8
4  = 100 (adds one)   = 1
5  = 101 (adds two)   = 3
6  = 110 (adds two)   = 5
7  = 111 (adds three) = 8

10 , 20     ---> 27
100 , 200   ---> 419
1 , 3       ---> 4
1 , 2       ---> 2
1000, 2000  ---> 5938

I have only explained the first example otherwise it would have taken up a huge amount of space if I tried to explain for all of them.


Note :

  • Numbers can be apart by over a 1000
  • All input will be valid.
  • The minimum output will be one.
  • You can accept number as an array of two elements.
  • You can choose how the numbers are ordered.

Winning criteria :

This is so shortest code in bytes for each language wins.

Muhammad Salman

Posted 2018-06-05T15:23:28.767

Reputation: 2 361

1OEIS A000788 – Leaky Nun – 2018-06-05T15:50:21.333

1May we take the input as some kind of range type (IntRange in Kotlin, Range in Ruby)? – snail_ – 2018-06-06T04:03:17.287

Fun fact: case 1000 - 2000 yields 5938, but lower the case by 1000, the result also drops by 1000: 0-1000 = 4938. Proof

– steenbergh – 2018-11-16T13:00:45.327

Answers

9

JavaScript (ES6), 38 bytes

Takes input in currying syntax (a)(b).

a=>b=>(g=c=>a>b?0:1+g(c^c&-c||++a))(a)

Try it online!

Commented

a => b => (         // given the input values a and b
  g = c =>          // g = recursive function taking c = current value
    a > b ?         // if a is greater than b:
      0             //   stop recursion and return 0
    :               // else:
      1 +           //   add 1 to the final result
      g(            //   and do a recursive call to g() with:
        c ^ c & -c  //     the current value with the least significant bit thrown away
        || ++a      //     or the next value in the range if the above result is 0
      )             //   end of recursive call
)(a)                // initial call to g() with c = a

Arnauld

Posted 2018-06-05T15:23:28.767

Reputation: 111 334

6

Python 2, 47 bytes

f=lambda x,y:y/x and bin(x).count('1')+f(x+1,y)

Try it online!

Dennis

Posted 2018-06-05T15:23:28.767

Reputation: 196 637

1Clever trick to avoid >=... – Erik the Outgolfer – 2018-06-05T16:38:45.980

5

Java (JDK 10), 55 bytes

a->b->{int c=0;for(;a<=b;)c+=a.bitCount(b--);return c;}

Try it online!

Olivier Grégoire

Posted 2018-06-05T15:23:28.767

Reputation: 10 647

IntStream.range(a,b+1).map(Integer::bitCount).sum() – saka1029 – 2018-06-06T07:33:40.260

@saka1029 The imports are mandatory. So it's actually a->b->java.util.stream.IntStream.range(a,b+1).map(Integer::bitCount).sum(), for a whole 74 bytes. Even if the the import wasn't mandatory, the parameters are, so we'd have to write a->b->IntStream.range(a,b+1).map(Integer::bitCount).sum(), which counts as 57 bytes – Olivier Grégoire – 2018-06-06T07:38:29.690

You could also have a->b->IntStream.range(a,b+1).map(Long::bitCount).sum() for a 1 byte improvement. Marginal, but still one. – NotBaal – 2018-11-14T00:00:32.463

@NotBaal As mentioned by Olivier in the comment above, imports are mandatory, so it should be a->b->java.util.stream.IntStream.range(a,b+1).map(Long::bitCount).sum() (71 bytes). – Kevin Cruijssen – 2018-11-15T13:53:11.807

4

05AB1E, 4 bytes

ŸbSO

Try it online!

Mr. Xcoder

Posted 2018-06-05T15:23:28.767

Reputation: 39 774

Exactly the solution I got :). +1. – Magic Octopus Urn – 2018-06-07T18:37:34.930

4

MATL, 5 4 bytes

&:Bz

Try it online!

Thanks to Luis Mendo for saving a byte!

(implicit input a and b, a<b)
&:                              % two-element input range, construct [a..b]
  B                             % convert to Binary as a logical vector (matrix)
   z                            % number of nonzero entries
(implicit output of the result)

Giuseppe

Posted 2018-06-05T15:23:28.767

Reputation: 21 077

4

Python 2, 45 bytes

lambda x,y:`map(bin,range(x,y+1))`.count('1')

Try it online!

Dennis

Posted 2018-06-05T15:23:28.767

Reputation: 196 637

4

R, 41 34 bytes

function(a,b)sum(intToBits(a:b)>0)

Try it online!

Heavily inspired by the other R solution by ngm. This uses a different approach after the conversion to bits. Huge thanks to Giuseppe for hinting at a possible 34 bytes solution.

JayCe

Posted 2018-06-05T15:23:28.767

Reputation: 2 655

34 bytes is possible! I forget where I saw the trick (I know I didn't come up with it) but there's a trickier conversion to a summable vector -- I'll post if you/ngm can't find it. – Giuseppe – 2018-06-05T17:36:49.250

@Giuseppe Indeed! – JayCe – 2018-06-05T18:14:33.640

2

I got it down to 37 bytes using a technique that might otherwise be useful. Also discovered that sd and var coerce anything they can to double.

– ngm – 2018-06-05T18:14:55.773

You can use pryr::f to save 4 bytes: https://tio.run/##K/qfZvu/oKiyyMoqTaO4NFcjM68kJN8ps6RYI9EqSdPOQFPzf5qGiY65JleahqGBjpEBhAFiQZg6xhDKSPM/AA

– pajonk – 2018-06-06T07:27:05.207

@pajonk good point! But I'm trying to stick to the base R packages rather than R+pryr. I'm going to search on meta what can be considered "pure R". – JayCe – 2018-06-06T20:27:58.793

3

Jelly, 4 bytes

rBFS

Try it online!

Explanation

rBFS – Full program. Takes the two inputs from the commands line arguments.
r    – Range.
 B   – For each, convert to binary.
  FS – Flatten and sum.

Mr. Xcoder

Posted 2018-06-05T15:23:28.767

Reputation: 39 774

O_o , that was fast ? – Muhammad Salman – 2018-06-05T15:27:51.260

@MuhammadSalman Well, the challenge is also kind of trivial IMO. – Mr. Xcoder – 2018-06-05T15:28:48.283

It may be, but an answer a minute after posting. – Muhammad Salman – 2018-06-05T15:30:25.060

1@MuhammadSalman Yes, that's not really that fast for trivial challenges like this one; knowledge of Jelly also ensues. The real effort goes in e.g. the language of this month, QBasic. ;-) – Erik the Outgolfer – 2018-06-05T15:46:01.860

@EriktheOutgolfer : Can you answer this in QBasic / BrainF**k ? – Muhammad Salman – 2018-06-05T15:46:57.447

3

Python 3, 56 54 52 bytes

This can be golfed more imo. -2 Bytes thanks to Mr.Xcoder -2 More bytes thanks to M. I. Wright

lambda a,b:''.join(map(bin,range(a,b+1))).count('1')

Try it online!

Windmill Cookies

Posted 2018-06-05T15:23:28.767

Reputation: 601

3

Pyth, 8 7 bytes

1 byte thanks to Mr. Xcoder.

ssjR2}F

Try it online!

Leaky Nun

Posted 2018-06-05T15:23:28.767

Reputation: 45 011

3

APL (Dyalog Unicode), 16 bytes

{≢⍸(⍵⍴2)⊤⍺↓0,⍳⍵}

Try it online!

-1 thanks to H.PWiz.

Left argument = min
Right argument = max

Erik the Outgolfer

Posted 2018-06-05T15:23:28.767

Reputation: 38 134

2

R, 44 40 37 bytes

function(a,b)sum(c(0,intToBits(a:b)))

Try it online!

Previously:

function(a,b)sum(strtoi(intToBits(a:b)))
function(a,b)sum(as.integer(intToBits(a:b)))

ngm

Posted 2018-06-05T15:23:28.767

Reputation: 3 974

2

Stax, 6 bytes

çy╠Ƽ☻

Run and debug it

recursive

Posted 2018-06-05T15:23:28.767

Reputation: 8 616

2

APL+WIN, 33 26 bytes

Prompts for vector of integers:

+/,((↑v)⍴2)⊤(1↓v)+0,⍳-/v←⎕

Try it online! Courtesy of Dalog Classic

Explanation:

v←⎕ prompt for input of a vector of two integers max first

(v←1↓v)+0,⍳-/ create a vector of integers from min to max

(↑v)⍴2 set max power of 2 to max 

⊤ convert integers to a matrix of binaries

+/, convert matrix to a vector and sum

Graham

Posted 2018-06-05T15:23:28.767

Reputation: 3 184

2

Bash + common utilities, 50

jot -w%o - $@|tr 247356 1132|fold -1|paste -sd+|bc

Try it online!

Converting integers to binary strings is always a bit of pain in bash. The approach here is slightly different - convert the integers to octal, then replace each octal digit with the number of binary 1s it contains. Then we can just sum all converted digits

Digital Trauma

Posted 2018-06-05T15:23:28.767

Reputation: 64 644

2

Octave with Communication toolbox, 21 bytes

@(a,b)nnz(de2bi(a:b))

Try it online!

The code should be fairly obvious. Number of nonzero elements in the binary representation of each of the numbers in the range.

This would be @(a,b)nnz(dec2bin(a:b)-48) without the communication toolbox.

Stewie Griffin

Posted 2018-06-05T15:23:28.767

Reputation: 43 471

1

Husk, 4 bytes

Σṁḋ…

Try it online!

Explanation

Σṁḋ…
   …     Get the (inclusive) range.
 ṁḋ      Convert each to binary and concatenate.
Σ        Get the sum.

user48543

Posted 2018-06-05T15:23:28.767

Reputation:

1

Pari/GP, 31 bytes

Saved one byte thanks to Mr. Xcoder.

a->b->sum(i=a,b,sumdigits(i,2))

Try it online!

alephalpha

Posted 2018-06-05T15:23:28.767

Reputation: 23 988

1

Japt -x, 10 8 7 bytes

òV ®¤è1

Try it online!

Oliver

Posted 2018-06-05T15:23:28.767

Reputation: 7 160

18 bytes: òV m¤¬è1 – Shaggy – 2018-06-05T15:43:54.800

1

Proton, 40 37 bytes

x=>y=>str(map(bin,x..y+1)).count("1")

Try it online!

Mr. Xcoder

Posted 2018-06-05T15:23:28.767

Reputation: 39 774

1

Ruby, 38 bytes

->a,b{("%b"*(b-a+1)%[*a..b]).count ?1}

Try it online!

G B

Posted 2018-06-05T15:23:28.767

Reputation: 11 099

1

Japt -x, 8 7 bytes

Takes input as an array of 2 integers.

rõ ®¤¬x

Try it


Explanation

rõ          :Reduce by inclusive range
   ®        :Map
    ¤       :  Convert to binary string
     ¬      :  Split
      x     :  Reduce by addition
            :Implicitly reduce by addition and output

Shaggy

Posted 2018-06-05T15:23:28.767

Reputation: 24 623

1

PHP, 97 Bytes

(sure this can be shortened, but wanted to use the functions)

Try it online

Code

<?=substr_count(implode(array_map(function($v){return decbin($v);},
 range($argv[0],$argv[1]))),1);

Explanation

<?=
 substr_count(   //Implode the array and count every "1"
  implode(
    array_map(function($v){return decbin($v);}, //Transform every decimal to bin
          range($argv[0],$argv[1])   //generate a range between the arguments
     )
),1);   //count "1"'s

Francisco Hahn

Posted 2018-06-05T15:23:28.767

Reputation: 591

it seems you can just do this

– dzaima – 2018-06-05T17:07:45.153

For a second i absolutely forgot that you can set php function's name directly as a parameter :-( – Francisco Hahn – 2018-06-05T17:10:57.493

$argv[0] is the program name or "-"; You should work with $argv[1] and $argv[2]. And you can use join instead of implode, shortening this to 68 bytes: <?=substr_count(join(array_map(decbin,range($argv[1],$argv[2]))),1); – Titus – 2018-11-11T18:15:56.957

1

K (ngn/k), 19 13 bytes

{+//2\x_!1+y}

Try it online!

{ } is a function with arguments x and y

!1+y is the list 0 1 ... y

x_ drops the first x elements

2\ encodes each int as a list of binary digits of the same length (this is specific to ngn/k)

+/ sum

+// sum until convergence; in this case sum of the sum of all binary digit lists

ngn

Posted 2018-06-05T15:23:28.767

Reputation: 11 449

1

PowerShell, 72 bytes

param($x,$y)$x..$y|%{$o+=([convert]::ToString($_,2)-replace0).length};$o

Try it online!

Long because of the conversion to binary [convert]::ToString($_,2) and getting rid of the zeros -replace0. Otherwise we just take the input numbers, make a range $x..$y and for each number in the range convert it to binary, remove the zeros, take the .length thereof (i.e., the number of ones remaining), and add it to our $output.

AdmBorkBork

Posted 2018-06-05T15:23:28.767

Reputation: 41 581

try to use count instead length :) – mazzy – 2018-07-02T13:40:50.470

1@mazzy count will always be 1 because we're counting the length of a string, not an array. – AdmBorkBork – 2018-07-02T13:43:51.177

string! you are right. thanks. -replace0 is smart. – mazzy – 2018-07-02T14:04:29.510

1

Haskell, 42 bytes

import Data.Bits
a%b=sum$popCount<$>[a..b]

Try it online!

Angs

Posted 2018-06-05T15:23:28.767

Reputation: 4 825

1

Pip, 10 bytes

$+JTB:a\,b

Try it online!

Explanation

            a and b are command-line args (implicit)
      a\,b  Inclusive range from a to b
   TB:      Convert to binary (: forces TB's precedence down)
  J         Join into a single string of 1's and 0's
$+          Sum (fold on +)

DLosc

Posted 2018-06-05T15:23:28.767

Reputation: 21 213

1

J, 16, 15 14 bytes

1 byte saved thanks to FrownyFrog!

+/@,@#:@}.i.,]

Try it online!

Explanation:

A dyadic verb, the left argument is the lower bound m of the range, the right one - the upper n.

            ,    append                      
             ]   n to the
          i.     list 0..n-1
         }.      drop m elements from the beginning of that list 
      #:@        and convert each element to binary 
    ,@           and flatten the table
 +/@             and find the sum

Galen Ivanov

Posted 2018-06-05T15:23:28.767

Reputation: 13 815

Can you make it 14? – FrownyFrog – 2018-06-07T09:31:34.310

@FrownyFrog I'll try later today (apparently it's possible, since you are asking :) ) – Galen Ivanov – 2018-06-07T10:11:54.833

@FrownyFrog 15 for now, I'm still trying...

– Galen Ivanov – 2018-06-07T14:28:41.740

114 – FrownyFrog – 2018-06-08T01:42:51.890

@FrownyFrog Aah, so easy! I was thinking about }. but always in a fork and not in a hook. Thanks! – Galen Ivanov – 2018-06-08T06:51:22.953

1

Perl 6, 32 30 bytes

-1 bytes thanks to Brad Gillbert

{[…](@_)>>.base(2).comb.sum}

Try it online!

Explanation:

[…](@_)    #Range of parameter 1 to parameter 2
       >>    #Map each number to
                      .sum  #The sum of
                 .comb      #The string of
         .base(2)    #The binary form of the number

Jo King

Posted 2018-06-05T15:23:28.767

Reputation: 38 234

1You can reduce it by one byte if you use [...](@_) instead of ($^a..$^b) – Brad Gilbert b2gills – 2018-06-07T17:00:52.037

1

Charcoal, 10 bytes

IΣ⭆…·NN⍘ι²

Try it online! Link is to verbose version of code. Explanation:

     NN     Input numbers
   …·       Inclusive range
  ⭆         Map over range and join
        ι   Current value
         ²  Literal 2
       ⍘    Convert to base as string
 Σ          Sum of digits
I           Cast to string
            Implicitly print

Neil

Posted 2018-06-05T15:23:28.767

Reputation: 95 035

1

Bash + coreutils, 38 32 bytes

seq -f2o%.fn $*|dc|tr -d 0|wc -c

Thanks to @Cowsquack for golfing off 6 bytes!

Try it online!

Dennis

Posted 2018-06-05T15:23:28.767

Reputation: 196 637

Nice approach, you can use dc to shave 6 bytes, seq -f2o%fp $*|dc|tr -cd 1|wc -c

– user41805 – 2018-06-06T12:05:28.043

1

Brachylog, 8 bytes

⟦₂ḃᵐcọht

Try it online!

Explanation

⟦₂         Ascending range between the two elements in the input
  ḃᵐ       Map to base 2
    c      Concatenate
     ọ     Occurrences of each element
      h    Head: take the list [1, <number of occurrences of 1>]
       t   Tail: the number of occurrences of 1

Fatalize

Posted 2018-06-05T15:23:28.767

Reputation: 32 976

1

QBasic, 95 93 83 82 bytes

@DLosc saved me some a lot of bytes!

Saved another byte using this technique!

INPUT a,b
FOR i=a TO b
k=i
FOR j=i TO 0STEP-1
x=k>=2^j
s=s-x
k=k+x*2^j
NEXT j,i
?s

Language of the Month FTW!

Explanation

INPUT a,b           Ask user for lower and upper bound
FOR i=a TO b        Loop through that range
k=i                 we need a copy of i to not break the FOR loop
FOR j=i TO 0STEP-1  We're gonna loop through exponents of 2 from high to low.
                    Setting the first test up for 4 to 2^4 (etc) we know we're overshooting, but that 's OK
x=k>=2^j            Test if the current power of 2 is equal to or smaller than k 
                    (yields 0 for false and -1 for true)
s=s-x               If k is bigger than 2^j, we found a 1, so add 1 to our running total s
                    (or sub -1 from the total s...)
k=k+x*2^j           Lower k by that factor of 2 if the test is true, else by 0
NEXT                Test the next exponent of 2
NEXT                process the next number in range
?s                  print the total

Last testcase of 1000 to 2000 actually works, in QBasic 4.5 running on Dosbox: Hij doet het!

steenbergh

Posted 2018-06-05T15:23:28.767

Reputation: 7 772

1

APL (Dyalog Extended), 6 bytesSBCS

≢⍤⍸⍤⊤…

Try it online!

 tally

 of

 where true

 in

 the binary representation of

 the range

Adám

Posted 2018-06-05T15:23:28.767

Reputation: 37 779

1… and it looks cute too – Adám – 2018-11-11T16:44:51.907

1

6510 machine code, 29 28 bytes

sub routine;
takes input from A (lower bound) and X (upper bound) registers;
returns result in A (MSB) and Y (LSB)

machine code:

85 02 A0 00 84 FC E8 CA
E4 02 30 OD 8A F0 F8 46
90 FB E8 90 F8 E6 FC D0
F4 A5 FC 60

source code:

        STA $02     store lower bound in $02
        LDY #0      init result to 0 (Y = LSB, $FC=MSB)
        STY $FC
        INX         increment upper bound
LOOP1:  DEX         decrement upper bound
        CPX $02     compare to lower bound
        BMI :FINISH if smaller, return
        TXA         copy X to A
LOOP2:  BEQ :LOOP1  if 0, next outer loop
        LSR         shift right
        BCC :LOOP2  if carry is clear, next inner loop
        INY         else increment result
        BCC :LOOP2
        INC $FC
        BNE :LOOP2  next inner loop
FINISH: LDA $FC
        RTS

notes

  • With only 8 bit input possible, the maximum number of set bits is 1024; so incrementing the MSB (INC $FC) always has a non-zero result; hence BNE :LOOP always branches.
  • BEQ following that BNE never branches, even not if the accumulator is zero (so I could actually add two to the BEQ parameter and save one cycle); but that doesn´t matter: LSR will clear the carry and set the zero flag, BCC will hop to LOOP2 and the BEQ to LOOP1.
  • I´m not completely sure (it´s been so long I actually coded on the C64), but it may fail if the range is larger than 127: CPX $02 is actually a substraction; if the result is >127, the negative flag may be set, so BMI would end the routine.
  • I hope I got the branching parameters correct - I assembled the machine code manually.

Titus

Posted 2018-06-05T15:23:28.767

Reputation: 13 814

0

Retina 0.8.2, 43 bytes

\d+
$*
M!&`(?<=^(1+),.*)\1.*
+`(1+)\1
$1x
1

Try it online!

Leaky Nun

Posted 2018-06-05T15:23:28.767

Reputation: 45 011

42 bytes – Neil – 2018-06-05T23:57:37.303

0

RProgN 2, 10 bytes

R²2Br.`0-L

Try it online!

ATaco

Posted 2018-06-05T15:23:28.767

Reputation: 7 898

0

C (GCC), 49 bytes

This function takes lower (a) and upper (b) bounds. Output is either through global c or by return value (if your ABI uses the same register from accumulating and function return).

c;f(a,b){for(c=b-a?f(a+1,b):0;a;a/=2)c+=a&1;a=c;}

Try It Online (output by return value)

Acknowledgments

Jakob

Posted 2018-06-05T15:23:28.767

Reputation: 2 428

150 bytes: c;f(a,b){c=b-a?f(a+1,b):0;for(;a;a/=2)c+=a&1;a=c;} – GPS – 2018-11-15T14:41:48.270

0

Javascript ES6, 78 bytes

With currying syntax

x=>y=>[...Array(y-x+1)].map((e,i)=>(i+x).toString`2`).join``.split`1`.length-1

MattH

Posted 2018-06-05T15:23:28.767

Reputation: 171

0

Red, 82 bytes

func[a b][s: 0 until[n: a until[if n % 2 = 1[s: s + 1]1 > n: n / 2]b < a: a + 1]s]

Try it online!

Galen Ivanov

Posted 2018-06-05T15:23:28.767

Reputation: 13 815

0

F#, 80 bytes

let c s e=Seq.sumBy(fun x->seq{for i=0 to 31 do yield x>>>i&&&1}|>Seq.sum){s..e}

Try it online!

For each number x in the range, shift the number by i bytes, AND it with 1, and add that to the sum for that number. Finally add all the shifting results for each number and return it.

It does the shift 32 times, since the starting and ending numbers are of type int32.

Ciaran_McCarthy

Posted 2018-06-05T15:23:28.767

Reputation: 689

0

Forth (gforth), 69 bytes

: f 1+ 0 -rot swap do i begin 2 /mod -rot + swap ?dup 0= until loop ;

Try it online!

Explanation

The basic algorithm is to loop over every number in range, and sum the binary digits (divide by two, add remainder to sum, repeat until number is 0)

Code Explanation

1+                   \ add one to the higher number to make it inclusive
0 -rot swap          \ create a sum value of 0 and put loop parameters in high low order
do                   \ start a loop over the range provided
  i                  \ place the index on the stack
  begin              \ start an indefinite loop
    2 /mod           \ get the quotient and remainder of dividing by 2
    -rot             \ move the quotient to the back
    + swap           \ add the remainder to the sum and move it down the stack
    ?dup             \ duplicate the quotient unless it equals 0
    0=               \ check if it equals 0
  until              \ if it does equal 0, end the inner loop
loop                 \ end the outer loop

reffu

Posted 2018-06-05T15:23:28.767

Reputation: 1 361

0

sed 4.2.2, 59

:
s/\b(1+) (11\1)/\1 1\1 \2/
t
:a
s/(1+)\1/\10/
ta
s/0| //g

Try it online!

Input and output as unary. Input is two space-separated unary integers.

The TIO has a footer line to convert to decimal, as a convenience.

The 1000, 2000 testcase takes too long - TIO times out after 1 minute.

Digital Trauma

Posted 2018-06-05T15:23:28.767

Reputation: 64 644

0

Tcl, 80 bytes

proc P a\ b {while \$a<=$b {incr c [regexp -all 1 [format %b $a]]
incr a}
set c}

Try it online!

sergiol

Posted 2018-06-05T15:23:28.767

Reputation: 3 055

0

Julia 0.6, 28 bytes

(a,b)->sum(count_ones.(a:b))

Try it online!


If input can be sent in in the form of a range (i.e. c(4:7) instead of c(4,7)), that saves 6 bytes:

Julia 0.6, 22 bytes

r->sum(count_ones.(r))

Try it online!

sundar - Reinstate Monica

Posted 2018-06-05T15:23:28.767

Reputation: 5 296

0

Powershell, 59 58 bytes

param($n,$m)$n..$m|%{for(;$_){$s+=$_-band1;$_=$_-shr1}};$s

Test script:

$f = {
param($n,$m)$n..$m|%{for(;$_){$s+=$_-band1;$_=$_-shr1}};$s
}

@(
,(4,7,8)
,(10,20,27)
,(100,200,419)
,(1,3,4)
,(1,2,2)
,(1000,2000,5938)
) | % {
    $n,$m,$e=$_
    $r = &$f $n $m
    $c = $r -eq $e

    "$c : $n , $m ---> $e = $r"
}

Output:

True : 4 , 7 ---> 8 = 8
True : 10 , 20 ---> 27 = 27
True : 100 , 200 ---> 419 = 419
True : 1 , 3 ---> 4 = 4
True : 1 , 2 ---> 2 = 2
True : 1000 , 2000 ---> 5938 = 5938

mazzy

Posted 2018-06-05T15:23:28.767

Reputation: 4 832

0

Pyt, 3 bytes

Input is the larger number then the smaller number

ŘĦƩ

Explanation:

      Implicitly get the two numbers x and y (x<y)
Ř     Push [x,x+1,...,y]
Ħ     Get the Hamming weight of each element of the array
Ʃ     Sum the list of Hamming weights
      Implicit output

Try it online!

mudkip201

Posted 2018-06-05T15:23:28.767

Reputation: 833

0

x86 machine code, 14 bytes

00000000: 31c0 f30f b8d9 01d8 4139 d17e f5c3       1.......A9.~..

Takes bottom of range in ecx, and top of range in ebx. Returns in eax.

Assembly (NASM syntax):

section .text
	global func
func:
					;1st arg = ecx, 2nd arg = edx
	xor eax, eax			;reset total
	loop:
		popcnt ebx, ecx		;get number of binary 1's in current number and store in ebx
		add eax, ebx		;add ebx to total (eax)
		inc ecx			;increase the current number (ecx) in range
		cmp ecx, edx
		jle loop		;repeat while current number (ecx) >= range max (edx)
	ret				;return the register eax

Try it online!

C code equivalent:

/*
ecx=range_start
edx=range_end
eax=total
ebx=ones_count
*/

int ones_in_range(int range_start, int range_end){
	int total = 0;
	do {
		int ones_count = __builtin_popcount(range_start);
		total += ones_count;
		range_start++;	
	} while(range_start <= range_end);
	return total;
}

Logern

Posted 2018-06-05T15:23:28.767

Reputation: 845

0

APL(NARS), 15 chars, 30 bytes

{+/∊(⍵⍴2)⊤⍺..⍵}

test

  f←{+/∊(⍵⍴2)⊤⍺..⍵}
  1000 f 2000
5938

This seems ok even in the case 0 f 0 because +/⍬ is 0.

RosLuP

Posted 2018-06-05T15:23:28.767

Reputation: 3 036

0

PHP, 68 bytes

The mapping variant already has been posted (though not yet in it´s mostly golfed version), so here is a looping solution:

for($i=$argv[2];$i>=$argv[1];)for($n=$i--;$n;$n>>=1)$s+=$n&1;echo$s;

Run with -nr or try it online.

Titus

Posted 2018-06-05T15:23:28.767

Reputation: 13 814

0

Perl 5 -p, 39 bytes

map$\+=(sprintf'%b',$_)=~y/1//,$_..<>}{

Try it online!

Xcali

Posted 2018-06-05T15:23:28.767

Reputation: 7 671

0

C# (.NET Core) with LINQ, 82 bytes

(a,b)=>{int c=0;for(;a<=b;a++)c+=Convert.ToString(a,2).Count(x=>x=='1');return c;}

Try it online!

Ungolfed:

(a, b) => {                     // takes in two integer inputs, separated by a comma
    int c = 0;                  // initialize the sum variable
    for(; a <= b; a++)          // from a (inclusive) to b (exclusive)
        c +=                            // add to c:
            Convert.ToString(a, 2)          // convert a to binary
                .Count(x => x == '1');      // count the number of ones in the binary form
    return c;                   // print c after the loop
}

Meerkat

Posted 2018-06-05T15:23:28.767

Reputation: 371

0

Burlesque - 12 bytes

per@b2\['1CN

pe             Parse eval
  r@           range
    b2         convert to base2
      \[       concat
        '1CN   count the `1`.

Try it online.

mroman

Posted 2018-06-05T15:23:28.767

Reputation: 1 382