| Bytes | Lang | Time | Link |
|---|---|---|---|
| 021 | GolfScript | 241227T020355Z | ErikDaPa |
| 080 | CASIO BASIC CASIO fx9750GIII | 241224T194452Z | madeforl |
| 007 | Uiua | 241224T174855Z | noodle p |
| 043 | Zsh | 241224T085754Z | roblogic |
| 006 | Japt x | 180605T154128Z | Shaggy |
| 054 | Swift 5.9 | 240325T130111Z | macOSist |
| 026 | Juby | 240319T204658Z | Jordan |
| 050 | Rust | 230914T150724Z | SaNoy Sa |
| 007 | MathGolf | 230914T134248Z | Kevin Cr |
| 015 | Aya | 230914T125306Z | lyxal |
| 004 | Thunno 2 S | 230622T170808Z | The Thon |
| 043 | Prolog SWI | 220827T022607Z | naffetS |
| 002 | Vyxal d | 220826T231416Z | tybocopp |
| 044 | Scala | 200807T184314Z | user |
| 028 | Wolfram Language Mathematica | 200807T065233Z | ZaMoC |
| 016 | x8616 machine code | 200702T181313Z | 640KB |
| 014 | x86 machine code | 181111T041926Z | user3604 |
| 058 | Powershell | 180702T133732Z | mazzy |
| 007 | Japt x | 180605T153745Z | Oliver |
| 049 | C GCC | 180605T171629Z | Jakob |
| 012 | Burlesque | 181115T110634Z | mroman |
| 082 | C# .NET Core with LINQ | 181114T164146Z | Meerkat |
| 039 | Perl 5 p | 181113T233649Z | Xcali |
| 028 | 6510 machine code | 181111T201332Z | Titus |
| 068 | PHP | 181111T182439Z | Titus |
| 030 | APLNARS | 181111T161625Z | user5898 |
| 006 | APL Dyalog Extended | 181111T164439Z | Adá |
| 003 | Pyt | 180822T192703Z | mudkip20 |
| 031 | Pari/GP | 180605T153553Z | alephalp |
| 082 | QBasic | 180606T194418Z | steenber |
| 014 | J | 180605T190803Z | Galen Iv |
| 028 | Julia 0.6 | 180608T004821Z | Sundar R |
| 080 | Tcl | 180608T000256Z | sergiol |
| 030 | Perl 6 | 180605T231840Z | Jo King |
| 013 | K ngn/k | 180605T165149Z | ngn |
| 032 | Bash + coreutils | 180606T032437Z | Dennis |
| 059 | sed 4.2.2 | 180606T221910Z | Digital |
| 080 | F# | 180605T232842Z | Ciaran_M |
| 069 | Forth gforth | 180606T212517Z | reffu |
| 008 | Brachylog | 180606T073112Z | Fatalize |
| 052 | Python 3 | 180605T153253Z | Windmill |
| 010 | Charcoal | 180606T000237Z | Neil |
| 037 | Proton | 180605T153752Z | Mr. Xcod |
| 082 | Red | 180605T193330Z | Galen Iv |
| 078 | Javascript ES6 | 180605T184026Z | MattH |
| 021 | Octave with Communication toolbox | 180605T183734Z | Stewie G |
| 010 | Pip | 180605T183017Z | DLosc |
| 034 | R | 180605T172008Z | JayCe |
| 037 | R | 180605T160441Z | ngm |
| 026 | APL+WIN | 180605T161207Z | Graham |
| 042 | Haskell | 180605T175928Z | Angs |
| 050 | Bash + common utilities | 180605T174146Z | Digital |
| 016 | APL Dyalog Unicode | 180605T165703Z | Erik the |
| 004 | MATL | 180605T154631Z | Giuseppe |
| 045 | Python 2 | 180605T171333Z | Dennis |
| 010 | RProgN 2 | 180605T171034Z | ATaco |
| 038 | JavaScript ES6 | 180605T154016Z | Arnauld |
| 043 | Retina 0.8.2 | 180605T170516Z | Leaky Nu |
| 047 | Python 2 | 180605T154742Z | Dennis |
| 072 | PowerShell | 180605T170029Z | AdmBorkB |
| 097 | PHP | 180605T164249Z | Francisc |
| 006 | Stax | 180605T160706Z | recursiv |
| 007 | Pyth | 180605T154244Z | Leaky Nu |
| 055 | Java JDK 10 | 180605T153647Z | Olivier |
| 038 | Ruby | 180605T154021Z | G B |
| 004 | 05AB1E | 180605T153051Z | Mr. Xcod |
| 004 | Husk | 180605T152845Z | user4854 |
| 004 | Jelly | 180605T152707Z | Mr. Xcod |
GolfScript, 21 bytes
1$-),{1$+2base~}%{+}*
Explanation:
1$-),{1$+2base~}%{+}*
1$-), => [0...difference]
{1$+2base~}% => add and convert to binary, then flatten
{+}* => sum
\; => keep only the result on the stack (optional)
CASIO BASIC (CASIO fx-9750GIII), 80 bytes
?→A
?→B
For A→X To B
logab(2,X
O+X-Σ(X Int÷ 2^N,N,1,1+Int Ans→O
Next
80 bytes
?→A
?→B
For A→X To B
Ans+X
For 1→N To logab(2,X
Ans-X Int÷ 2^N
Next
Next
uses the following equasion for both of them $$ f(a,b) = \sum_{x=a}^{b}(x-\sum_{n=1}^{\left\lceil log_2(x)\right\rceil}\left\lfloor \frac{x}{2^n}\right\rfloor) $$ (thanks to mego for helping me w the math and stuffs)
Uiua, 7 bytes
⧻⊚⋯⊂⊸⍜-⇡
Try it: Uiua pad
The function ⇡ range gives the range [0, a). ⍜-⇡ "under subtract range" subtracts one number from the other, takes the range, and adds the number back to each element, giving the range [a, b). ⊂⊸ appends b to the array again, giving the range [a, b] as needed.
⋯ bits converts an array of numbers into an array of arrays of the binary representation of each.
⧻⊚ "length where" gives the total number of ones in this 2d array.
Zsh, 43 bytes
for i ({$1..$2})H+=${$(([##2]i))//0}
<<<$#H
Iterations over i build up H, a string of 1s. Then we print the length of H.
Japt -x, 8 7 6 bytes
õV cì2
õV cì2 :Implicit input of integers U & V
õV :Range [U,V]
c :Flat map
ì2 : Convert to binary digit array
:Implicit output of sum
Swift 5.9, 54 bytes
let f={($0+0...$1+0).reduce(0){$0+$1.nonzeroBitCount}}
f(_:_:) takes a lower bound and an upper bound.
There aren't really any fancy tricks here, just a simple call to reduce(_:_:) and some hints for the type checker in the form of +0s.
Rust, 54 50 btyes
|l:u32,h:u32|(l..=h).fold(0,|c,x|c+x.count_ones())
count_ones does the heavy lifting of counting the number of ones in each number here.
Used fold to avoid turbofish from sum.
Ungolfed:
|low: u32, high: u32| (low..=high).fold(0, |total, x| total + x.count_ones())
MathGolf, 7 bytes
╒k(≥mâΣ
Takes two loose inputs in reversed order.
Explanation:
Unfortunately, MathGolf lacks a ranged-list builtin, so 4 bytes are used for that..
╒k(≥ # Push a list in the range [secondInput,firstInput]:
╒ # Push a list in the range [1, (first) implicit input-integer]
k # Push the second input-integer
( # Decrease it by 1
≥ # Remove that many leading items from the ranged-list
m # Map over each integer in this list:
â # Convert it to a binary-list
Σ # Take the flattened sum of this list of lists of bits
# (after which the entire stack is output implicitly as result)
Aya, 15 bytes
[2|,10 2.&].FW
Apparently there's no to binary built-in, so it needs to be done manually. Takes inputs on the stack.
Example Session
Given that there's no try it online, I figured I'd provide an example console session, placing the program in a function for convenience. It would work outside the function and without the variable names, as taking input from the stack is an allowed default for stack languages.
aya> {a b, a b[2|,10 2.&].FW} :f
{a b, a b [2|, 10 2 .&] .F W}
aya> 4 7 f
8
aya> 10 20 f
27
aya> 100 200 f
419
aya> 1 3 f
4
aya> 1 2 f
2
aya> 1000 2000 f
5938
Explained
[2|,10 2.&].FW
[2|, ] # Over each number in a range from the first input to the second
.& # Convert the number
10 # From base 10
2 # To base 2
.F # Flatten the resulting list
W # And summate
💎
Created with the help of Luminespire.
Thunno 2 S, 4 bytes
I2Bʂ
Explanation
I2Bʂ # Implicit input
I # Inclusive range
2B # Convert each to binary
ʂ # Sum each inner list
# Implicit output of sum
Vyxal d, 2 bytes
ṡb
Try it online or see a four byte flagless version.
Gets the range between the two inputs, converts each to a list of 1s and 0s, then deep flattens and sums with the d flag.
x86-16 machine code, 16 bytes
Binary:
00000000: 33c0 8bd1 d1e2 7301 4075 f93b cbe0 f3c3 3.....s.@u.;....
Listing:
33 C0 XOR AX, AX ; clear 1's counter in AX
INTLOOP:
8B D1 MOV DX, CX ; current number into DX
BITLOOP:
D1 E2 SHL DX, 1 ; MSb into CF, ZF = ( DX == 0 )
73 01 JNC BITZERO ; if a zero, check ZF
40 INC AX ; increment counter
BITZERO:
75 F9 JNZ BITLOOP ; if DX > 0 keep looping
3B CB CMP CX, BX ; is CX < BX?
E0 F3 LOOPNZ INTLOOP ; if not, decrement CX and loop
C3 RET ; return to caller
Callable function, low range number in BX, high number in CX. Result in AX.
Note: There is another IA machine code submission which uses the POPCNT instruction introduced with SSE4 requiring an Intel Core or later architecture. This one will run on any 8086 or later CPU.
Test program:
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
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;
}
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
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
- -5 bytes thanks to GPS
- -1 byte thanks to ceilingcat
Burlesque - 12 bytes
per@b2\['1CN
pe Parse eval
r@ range
b2 convert to base2
\[ concat
'1CN count the `1`.
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;}
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
}
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; henceBNE :LOOPalways branches. BEQfollowing thatBNEnever 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:LSRwill clear the carry and set the zero flag,BCCwill hop toLOOP2and theBEQtoLOOP1.- 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 $02is actually a substraction; if the result is >127, the negative flag may be set, soBMIwould end the routine. - I hope I got the branching parameters correct - I assembled the machine code manually.
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.
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.
APL (Dyalog Extended), 6 bytesSBCS
≢⍤⍸⍤⊤…
≢ tally
⍤ of
⍸ where true
⍤ in
⊤ the binary representation of
… the range
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
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:

J, 16, 15 14 bytes
1 byte saved thanks to FrownyFrog!
+/@,@#:@}.i.,]
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
Julia 0.6, 28 bytes
(a,b)->sum(count_ones.(a:b))
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))
Tcl, 80 bytes
proc P a\ b {while \$a<=$b {incr c [regexp -all 1 [format %b $a]]
incr a}
set c}
Perl 6, 32 30 bytes
-1 bytes thanks to Brad Gillbert
{[…](@_)>>.base(2).comb.sum}
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
K (ngn/k), 19 13 bytes
{+//2\x_!1+y}
{ } 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
Bash + coreutils, 38 32 bytes
seq -f2o%.fn $*|dc|tr -d 0|wc -c
Thanks to @Cowsquack for golfing off 6 bytes!
sed 4.2.2, 59
:
s/\b(1+) (11\1)/\1 1\1 \2/
t
:a
s/(1+)\1/\10/
ta
s/0| //g
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.
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}
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.
Forth (gforth), 69 bytes
: f 1+ 0 -rot swap do i begin 2 /mod -rot + swap ?dup 0= until loop ;
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
Brachylog, 8 bytes
⟦₂ḃᵐcọht
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
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')
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
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]
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
Octave with Communication toolbox, 21 bytes
@(a,b)nnz(de2bi(a:b))
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.
Pip, 10 bytes
$+JTB:a\,b
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 +)
R, 41 34 bytes
function(a,b)sum(intToBits(a:b)>0)
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.
R, 44 40 37 bytes
function(a,b)sum(c(0,intToBits(a:b)))
Previously:
function(a,b)sum(strtoi(intToBits(a:b)))
function(a,b)sum(as.integer(intToBits(a:b)))
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
Bash + common utilities, 50
jot -w%o - $@|tr 247356 1132|fold -1|paste -sd+|bc
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
APL (Dyalog Unicode), 16 bytes
{≢⍸(⍵⍴2)⊤⍺↓0,⍳⍵}
-1 thanks to H.PWiz.
Left argument = min
Right argument = max
MATL, 5 4 bytes
&:Bz
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)
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)
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
PowerShell, 72 bytes
param($x,$y)$x..$y|%{$o+=([convert]::ToString($_,2)-replace0).length};$o
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.
PHP, 97 Bytes
(sure this can be shortened, but wanted to use the functions)
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
Husk, 4 bytes
Σṁḋ…
Explanation
Σṁḋ…
… Get the (inclusive) range.
ṁḋ Convert each to binary and concatenate.
Σ Get the sum.
Jelly, 4 bytes
rBFS
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.
