| Bytes | Lang | Time | Link |
|---|---|---|---|
| 068 | Tcl | 250604T210453Z | sergiol |
| 066 | Google Sheets / Excel | 250607T004420Z | z.. |
| 037 | AWK | 250606T233633Z | xrs |
| 028 | Swift 6 | 250502T180632Z | macOSist |
| 008 | Thunno 2 L | 230509T175948Z | The Thon |
| 6125 | Vyxal l | 230509T175146Z | emirps |
| 065 | awk | 221101T133707Z | RARE Kpo |
| 010 | 386 opcode | 171228T144500Z | l4m2 |
| 012 | MathGolf | 190320T143404Z | maxb |
| 037 | Forth gforth | 190319T150804Z | reffu |
| 014 | dc | 190319T144835Z | Sophia L |
| 020 | ><> | 190319T142656Z | Emigna |
| 034 | brainfuck | 171229T031833Z | Jo King |
| 032 | J | 171229T014016Z | Bolce Bu |
| nan | JavaScript | 171228T150403Z | l4m2 |
| 066 | SNOBOL4 CSNOBOL4 | 171228T143115Z | Giuseppe |
| 026 | Mathematica | 120926T220646Z | DavidC |
| 012 | Pushy | 171227T183315Z | FlipTack |
| 025 | Python 2 | 170720T192556Z | Koishore |
| 036 | PHP | 170720T193106Z | halfmang |
| 066 | C | 120101T101911Z | Paul R |
| 030 | TIBasic TI84 Plus CE | 170331T163955Z | pizzapan |
| 036 | Java 7 | 161216T184652Z | Poke |
| 042 | JavaScript | 111230T153415Z | mellamok |
| 100 | sed | 160125T163516Z | Toby Spe |
| 050 | JavaScript | 150708T031329Z | Jamie |
| 002 | Brainbool | 150708T021302Z | lirtosia |
| 021 | GolfScript | 130503T080921Z | aditsu q |
| 026 | dc – | 121031T230656Z | daniero |
| 035 | excel | 121031T132733Z | SeanC |
| 045 | Ocaml | 120926T202725Z | ReyCharl |
| 019 | Op | 120225T003247Z | Ry- |
| 045 | C | 120123T174923Z | Mr. Llam |
| 057 | PHP | 120129T212618Z | Arjan |
| nan | Isn't reading a number into binary or printing the number from binary a "builtin base conversion function" | 120121T145934Z | Jeff Bur |
| nan | 120120T014928Z | Samuel D | |
| 052 | OCaml | 120103T004719Z | Leah Xue |
| 053 | C | 111231T013738Z | sam hoce |
| 060 | Haskell | 120101T152833Z | marinus |
| 053 | Brainfuck | 120101T152657Z | copy |
| 071 | JavaScript | 111230T223203Z | pimvdb |
| 012 | Common Lisp | 111231T041913Z | Joanis |
| 012 | APL | 111230T210652Z | Dillon C |
| 013 | J | 111230T182509Z | Gareth |
| 036 | Perl | 111230T154630Z | PhiNotPi |
| 030 | Perl | 111230T203918Z | Ilmari K |
| 016 | GolfScript | 111230T162124Z | Howard |
| 053 | R | 111230T185324Z | Brian Di |
| 065 | Python 48 without spaces | 111230T171153Z | elssar |
| 038 | Ruby | 111230T165920Z | Howard |
| 041 | Python 2.6 | 111230T164840Z | Steven R |
| 045 | Python 2.6 | 111230T161538Z | Steven R |
| 070 | D | 111230T161407Z | ratchet |
| 086 | Scala | 111230T154358Z | Gareth |
Tcl, 68 bytes
proc C n {while \$n {incr b [expr $n%2]
set n [expr $n/2]}
incr b 0}
proc C {n b\ 0} {while \$n {incr b [expr $n%2]
set n [expr $n/2]}
set b}
Google Sheets / Excel, 66 bytes
=LET(F,LAMBDA(F,q,r,IF(q/2,F(F,INT(q/2),r+MOD(q,2)),r)),F(F,A1,0))
AWK, 37 bytes
{for(x=0;$1=int($1/2);)x+=$1%2}1,$0=x
{for( # loop
x=0; # if input is zero
$1=int($1/2);) # binary breakdown
x+=$1%2} # add digit to total
1,$0=x # set output
Swift 6, 28 bytes
let f={$0<1 ?0:$0%2+f($0/2)}
This solution was 2 bytes shorter than using the builtin:
let f={($0+0).nonzeroBitCount}
Why Swift has a builtin for this, I'll never know.
Thunno 2 L, 8 bytes
LOʠæS=;Ḟ
Port of emirps's Vyxal answer.
Explanation
LOʠæS=;Ḟ # Implicit input
LO # Push 2 ** [0..input)
ʠ # Powerset of this list
æ ; # Filtered by:
S= # Sum equals the input
Ḟ # Flatten this list of lists
# L flag gets the length
# Implicit output
Screenshot
Vyxal l, 49 bits1, 6.125 bytes
ʀEṗ'∑?=;f
Brute force solution, so the online interpreter times out. May potentially be made shorter by porting others, but I thought this solution was fun
ʀ # range 0..input+1
E # raise 2^n for each value in that range
ṗ # powerset
' ; # filtered by
∑ # the sum
?= # is equal to the input?
f # flatten
# after which the l flag takes the length of the top of the stack and implicitly outputs it
awk, 65 bytes
__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""
Example:
echo "56432\n45781254\n0" |
mawk '__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""'
8
11
0
386 opcode, 10 Bytes
2BC0 SUB EAX,EAX
01C9 ADD ECX,ECX
1400 ADC AL,0
41 INC ECX
E2F9 LOOP $-5
C3 RET
Thank Peter Cordes for 1B save and 1B rule save
MathGolf, 12 bytes
æ_╫`¡▲ÞĽ↑;î
This fails for input 0, due to a bug in MathGolf. I'll explain why. But I thought it was a fun solution to this problem that might not be obvious.
This method could be seen as disallowed, but I refer to wikipedia: "The bit shifts are sometimes considered bitwise operations, because they treat a value as a series of bits rather than as a numerical quantity" (emphasis mine). I have chosen to interpret this to mean that MathGolf's bitshifts are allowed, since they don't operate on a fixed number of bytes. Bit rotating in MathGolf wraps the current number of bits in the number, and rotates using the bit width of the number. Thus, if you do this enough times, any number with \$n\$ set bits will converge to \$2^n-1\$. If you then divide the result by 2 until you reach 0, the number of divisions will represent the number of ones in the original number.
The reason that this fails for 0 is that 0 is somehow turned into 1 when left-rotated. This is a bug in the implementation of the operator, rather than this program itself, and should be fixed in an upcoming update.
Explanation
æ ▲ do-while true using 4 operators
_ duplicate TOS
╫ left-rotate bits in int, list/str
` duplicate the top two items
¡ push a, b, push a != b
This do-while loop repeats until the left-rotated
Þ not implemented yet
Ä start block of length 1
½ pop a : push(a//2 if int else a/2)
↑ while true without popping
; discard TOS
î index of current loop (1-based)
Forth (gforth), 37 bytes
: f dup 0> if 2 /mod recurse + then ;
Usually recursion isn't worth it when golfing Forth because it requires the if, then, (possible else), and recurse words. In this case we can do without else and we save more in stack-manipulation than we lose from recursion
Explanation
- If n is greater than 0, get quotient and remainder of dividing n by 2.
- Call recursively on quotient
- Add remainder to result
Code Explanation
: f \ start new word definition
dup \ duplicate top stack value
0> if \ if top stack value is greater than 0
2 /mod \ get quotient and remainder of dividing by 2 (quotient on top of stack)
recurse \ execute current word
+ \ add remainder to result of recursion
then \ end if statement
; \ end word definition
dc, 14 bytes
[2~rd0<M+]dsMx
Input is taken from the stack, output is left on the stack. This is the same general idea as the previous dc entry (repeatedly reduce mod 2 and add remainders), but optimizing by using non-tail recursion makes a huge difference (I'd have made this a comment on that entry, but the user hasn't been active for over a year).
brainfuck, 34 bytes
>+<[[>-]++[>]+[<]>-]>[-<[->+<]>>]<
At 53 bytes, I thought the existing brainfuck solution was way too long /s. Starting cell contains the number and ends on the number of binary digits in it. Doesn't work for numbers above 255 unless you use an interpreter with larger than 8 bit or infinite cells.
How It Works
>+<[[>-]++[>]+[<]>-] Converts the number to binary
>[-<[->+<]>>]< Adds all the numbers in the binary together
J, 32 Bytes
There's probably a more mathematical way to do this that doesn't require finding the binary representation, but I thought this was pretty good none the less:
+/@:((}:,(|~2:)@{:,<.@-:@{:)^:])
Explanation:
+/@:((}:,(|~2:)@{:,<.@-:@{:)^:]) | Full program
( ) | Convert to binary list:
( )^:] | do n times:
}: | Curtail the list
,(|~2:)@{: | Append the remainder mod 2 of the item dropped
,<.@-:@{: | Append the floor of half the item dropped
+/@: | Sum
A step by step example:
(}:,(|~2:)@{:,<.@-:@{:) 7
1 3
^ ^
| |
| Floor 7/2
7 % 2
(}:,(|~2:)@{:,<.@-:@{:) 1 3
1 1 1
^ ^ ^
| | |
| | Floor 3/2
| 3 % 2
The input curtailed
((}:,(|~2:^#)@{:,<.@-:@{:)^:]) 7
1 1 1 0 0 0 0 0
+/@:((}:,(|~2:)@{:,<.@-:@{:)^:]) 7
3
Of course, you would only have to do this Ceil(log2 n) times, but thats a lot harder to calculate than just n.
JavaScript, 43 Bytes, assuming 1/2/2/2/...=0
for(a=prompt(b=0);a;a/=2)b+=a%2>=1;alert(b)
SNOBOL4 (CSNOBOL4), 66 bytes
X =INPUT
I O =O + REMDR(X,2)
X =GT(X) X / 2 :S(I)
OUTPUT =O
END
Mathematica 26
Count[n~IntegerDigits~2,1]
Pushy, 12 bytes
$&2%v2/;O_S#
While the input is bigger than 0, it has its least significant bit (using mod) pushed to the second stack, then it is halved (integer division). Once all bits have been placed on the second stack, it is summed and the result is printed.
PHP, 36 bytes
while($n){$o+=$n%2;$n/=2*1;}echo $o;
Assumes $n is the number to be tested, shows a PHP Notice for $o, and doesn't exactly work when $n is 0 (outputs nothing).
PHP, 53 bytes
$n=$argv[1];$o=0;while($n){$o+=$n%2;$n/=2*1;}echo $o;
Accepts command-line input, doesn't show a PHP Notice, and outputs correctly for 0.
C, 66 characters
main(int n,char **a){printf("%u",__builtin_popcount(atoi(a[1])))};
Note: requires gcc or gcc-compatible compiler (e.g. ICC, clang).
For some CPUs __builtin_popcount compiles to a single instruction (e.g. POPCNT on x86).
TI-Basic (TI-84 Plus CE), 30 bytes
Prompt X
0→S
While X
S+remainder(2,X→S
int(X/2→X
End
S
TI-Basic is a tokenized language, all tokens but remainder( are one-byte, remainder is two
Java 7, 36 bytes
int b(Long a){return a.bitCount(a);}
Because of course this, of all things, is something that Java has a builtin for...
JavaScript, 49 47 45 42 bytes
for(n=prompt(o=0);n=n/2|0;o+=n%2);alert(o)
Demo: http://jsfiddle.net/hcYdx/4/
Edit 1: remove q and use ~~ for rounding, save 2 chars.
Edit 2: use |0 rounding operator instead of ~~ to save parentheses (2 chars).
Edit 3: simplify n>0 to n and combine with n=n/2|0 to make entire condition; now have wasted statement space :(
sed, 100 bytes
:
s/[13579]/&;/g
y/123456789/011223344/
s/;0/5/g
s/;1/6/g
s/;2/7/g
s/;3/8/g
s/;4/9/g
/[1-9]/b
s/0//g
Output is in unary; if you want it in decimal, pipe through wc -c or append the following converter (GNU sed -r):
# unary to decimal
:d
s/;;;;;/v/g
s/vv/x/g
s/x([0-9]|$)/x0\1/
s/;;/b/g
s/bb/4/
s/b;/3/
s/v;/6/
s/vb/7/
s/v3/8/
s/v4/9/
y/;bvx/125;/
td
This implements successive division by 2, accumulating carry-out as output. It is able to handle fairly large inputs; for example I tested the all-ones 8192-bit input thus:
$ dc <<<'2 8192^1-p' | tr -d '\\\n' | ./4434.sed | wc -c
8192
and the mostly-zeros of similar length:
$ dc <<<'2 8192^p' | tr -d '\\\n' | ./4434.sed | wc -c
1
JavaScript, 57 55 51 50 bytes
a=prompt(b=0);while(a){b+=a%2;a=(a-a%2)/2}alert(b)
Modulo is not bitwise operator ☺
Brainbool, 2
,.
The most reasonable interpretation, in my opinion (and what most of the answers use) of "highest number your language is able to handle" is "largest number your language natively supports". Brainbool is a brainfuck derivative that uses bits rather than bytes, and takes input and output in binary (0 and 1 characters) rather than character codes. The largest natively supported number is therefore 1, and the smallest is 0, which have Hamming weights 1 and 0 respectively.
Brainbool was created in 2010, according to Esolang.
GolfScript - 21
~{.2%{0):0;}*2/.}do;0
dc – 26 chars
This is rather long, mostly due to the lack of loop constructs in dc.
0?[d2%rsi+li2/d0<x]dsxx+p
Keeps adding up the modulo 2 of the number and dividing the number by to until it reaches zero. Can handle arbitrarily long integers.
Example:
$ dc -e '0?[d2%rsi+li2/d0<x]dsxx+p' <<< 127
7
$ dc countones.dc <<< 1273434547453452352342346734573465732856238472384263456458235374653784538469120235
138
excel, 35
=LEN(A1)-LEN(SUBSTITUTE(A1,"1",""))
Ocaml, 45 characters
Based on @Leah Xue's solution. Three spaces could be removed and it's sligthly shorter (~3 characters) to use function instead of if-then-else.
let rec o=function 0->0|x->(x mod 2)+(o(x/2))
Op, 23 19 (discontinued language of my invention)
0N[1~!?@2%{1+}2/])I
Here's a commented version:
0 # push a 0 onto the stack
N # read an integer from STDIN onto the stack
[ # begin an infinite loop
1 # push a 1 onto the stack
~ # pop the 1 off the stack, and duplicate the top 1 items (i.e. the read number)
! # pop a number, push 1 if 0 or 0 otherwise (NOT)
? # pop a number, if the number is nonzero...
@ # ... then break out of the infinite loop. Basically, break out when N reaches 0.
2 # push a 2 onto the stack
% # pop number "a" off the stack, then number "b", and push b modulo a.
{ # rotate the stack left
1 # push a 1 onto the stack
+ # pop a and b, and push a + b (increment)
} # rotate the stack right
2 # push a 2 onto the stack
/ # pop number "a" off the stack, then number "b", then push b / a (int)
] # repeat back to start of loop
) # shift the stack right, taking off the 0 and leaving only the result
I # output the result as a number to STDOUT
C, 45
f(n,c){for(c=0;n;n/=2)c+=n%2;printf("%d",c);}
Nothing really special here for golfing in C: implicit return type, implicit integer type for parameters.
PHP, 57
$i=$s=0;for(;$i<log($n,2);){$s+=$n/pow(2,$i++)%2;}echo$s;
This assumes that $n holds the value to be tested.
PHP, 55 (alternative solution)
function b($i){return$i|0?($i%2)+b($i/2):0;}echo b($n);
Again, this assumes that $n holds the value to be tested. This is an alternative because it uses the or-operator to floor the input.
Both solutions work and do not cause notices.
Isn't reading a number into binary or printing the number from binary a "builtin base conversion function", thus invalidating every answer above that prints an integer? If you permit reading and printing an integer, like almost all the above answers do, then I'll make claims using a builtin popcount function :
Haskell, 50
There was a popCount routine added to the Data.Bits module for GHC v7.2.1/v7.4.1 this summer (see tickets concerning the primop and binding).
import Data.Bits
main=interact$show.popCount.read
I cannot beat the above Python and Perl scores using their GMPY or GMP::Mpz modules for GMP sadly, although GMP does offer a popcount function too.
Scheme
I polished the rules a bit to add to the challenge. The function doesn't care about the base of the number because it uses its own binary scale. I was inspired by the way analog to numeric conversion works. I just use plain recursion for this:
(define (find-ones n)
(define (nbits n)
(let nbits ([i 2])
(if (< i n) (nbits (* i 2)) i)))
(let f ([half (/ (nbits n) 2)] [i 0] [n n])
(cond [(< half 2) i]
[(< n i) (f (/ half 2) i (/ n 2))]
[else (f (/ half 2) (+ i 1) (/ n 2))])))
OCaml, 52 characters
let rec o x=if x=0 then 0 else (x mod 2) + (o (x/2))
C, 61 60 57 53 characters
void f(x){int i=0;for(;x;x/=2)i+=x%2;printf("%u",i);}
The function body only is 38 characters. Edit: removed bitwise operator Edit: put printf out of the loop as suggested in the comments Edit: switch to K&R declaration; also, this is no longer C99-specific
Haskell (60 chars)
f n=sum[1|x<-[0..n],odd$n`div`2^x]
main=interact$show.f.read
Brainfuck, 53 characters
This was missing an obligatory Brainfuck solution, so I made this one:
[[->+<[->->>>+<<]>[->>>>+<<]<<<]>>>>[-<<<<+>>>>]<<<<]
Takes number from cell 1 and puts the result into cell 6.
Unenrolled and commented version:
[ while n != 0
[ div 2 loop
-
>+< marker for if/else
[->->>>+<<] if n != 0 inc n/2
>
[->>>>+<<] else inc m
<<<
]
>>>> move n/2 back to n
[-<<<<+>>>>]
<<<<
]
JavaScript, 78 72 71 characters
I'll post my initial solution which I came up with before posting the question as well. There is already a much better JavaScript answer though :)
for(n=prompt(a=0),j=1;j<=n;j*=2)for(i=j;i<=n;i+=2*j)n<i+j&&a++;alert(a)
The idea comes from certain "mind reading cards" which enable you to obtain the number someone else has in mind, by showing them cards and let them say on which cards their number is apparent.
It works because each number is a unique combination of 1s / 0s in binary. My solution checks on which "cards" the number is apparent so as to determine how many 1s it has. It's just not very efficient, though...
I found this document which outlines the mind reading technique.
Common Lisp, 12 chars
(assuming a 1 char variable name - i.e.: 11 + number length)
It's not a base conversion function, so it should work:
(logcount x)
Examples:
[1]> (logcount 0)
0
[2]> (logcount 1)
1
[3]> (logcount 1024)
1
[4]> (logcount 1023)
10
[5]> (logcount 1234567890123456789012345678901234567890)
68
(Using GNU CLISP.)
APL, 9 12 characters
+/2|⌊⎕÷2*⍳32
This assumes that the interpreter uses 32-bit integers, and that ⎕IO is set to 0 (meaning that monadic ⍳ begins with 0, rather than 1). I used the 32-bit version of Dyalog APL.
Explanation, from right to left:
⍳32generates a vector of the first32integers (as explained before, because⎕IOis 0, this vector begins with 0).*is the power function. In this case, it generates2to the power of each element of the vector supplied as its right argument.÷is the divided-by function. It gives us⎕(evaluated user input) divided by each element of the vector to its right (each power of two).⌊floors each element of the argument to its right.2|gives us the remainder of each element of to its right divided by2./reduces (folds) its right argument using the function to its left,+.
Not quite 9 characters anymore. :(
Old, rule-breaking version:
+/⎕⊤⍨32/2Explanation, from right to left:
32/2: Replicate2,32times.⍨commutes the dyadic function to its left, which in this case is⊤(i.e.,X⊤⍨Yis equivalent toY⊤X).⊤is the encode function. It encodes the integer to its right in the base given to its left. Note that, because of the commute operator, the right and left arguments are switched. The base is repeated for the number of digits required, hence32/2.⎕is a niladic function that accepts user input and evaluates it.+/reduces (folds) its right argument using+. (We add up the 0's and 1's.)
J, 13 characters
(+ the number of digits in the number)
+/2|<.n%2^i.32
Usage: replace the n in the program with the number to be tested.
Examples:
+/2|<.56432%2^i.32
8
+/2|<.45781254%2^i.32
11
+/2|<.0%2^i.32
0
There's probably a way of rearranging this so the number can be placed at the beginning or end, but this is my first J entry and my head's hurting slightly now.
Explanation(mainly so that I understand it in the future)
i.32 - creates an array of the numbers 1 to 32
2^ - turns the list into the powers of two 1 to 4294967296
n% - divides the input number by each element in the list
<. - rounds all the divison results down to the next integer
2| - same as %2 in most languages - returns 0 if even and 1 if odd
+/ - totals the items in the list (which are now just 1s or 0s)
Perl, 45 43 36 Characters
$n=<>;while($n){$_+=$n%2;$n/=2}print
Thanks to Howard for 45->43, and to User606723 for 43->36.
Perl, 30 chars
$==<>;1while$_+=$=%2,$=/=2;say
Based on PhiNotPi's solution, with some extra golfing. Run with perl -M5.010 to enable the Perl 5.10 say feature.
GolfScript, 17 16 characters
~{.2%\2/.}do]0-,
Edit: new version saves 1 character by using list operation instead of fold (original version was ~{.2%\2/.}do]{+}*, direct count version: ~0\{.2%@+\2/.}do;).
R, 53 characters
o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
Examples:
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 56432
2:
Read 1 item
[1] 8
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 45781254
2:
Read 1 item
[1] 11
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 0
2:
Read 1 item
[1] 0
If inputting the number is not part of the character count, then it is 43 characters:
o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0}
with test cases
> o(56432)
[1] 8
> o(45781254)
[1] 11
> o(0)
[1] 0
Python (48 without spaces, 65 with)
x = int(raw_input())
s = 0
while x:
if x%2:
s+=1
x/=2
print s
Ruby, 38 characters
f=->u{u<1?0:u%2+f[u/2]}
p f[gets.to_i]
Another solution using ruby and the same recursive approach as Steven.
Python 2.6, 41 characters
t,n=0,input()
while n:t+=n%2;n/=2
print t
note: My other answer uses lambda and recursion and this one uses a while loop. I think they are different enough to warrant two answers.
Python 2.6, 45 characters
b=lambda n:n and n%2+b(n/2)
print b(input())
D (70 chars)
int f(string i){int k=to!int(i),r;while(k){if(k%2)r++;k/=2;}return r;}
Scala, 86 characters
object O extends App{def f(i:Int):Int=if(i>0)i%2+f(i/2)else 0
print(f(args(0).toInt))}
Usage: scala O 56432
