Population count: Difference between revisions

m
typo
m (typo)
 
(89 intermediate revisions by 39 users not shown)
Line 1:
{{task}}[[Category:Mathematics]]
The ''[[wp:Hamming weight|population count]]'' &nbsp; is the number of &nbsp; <big>'''1'''</big>s &nbsp; (ones) &nbsp; in the binary representation of a non-negative integer.
 
{{task}}
''Population count'' is also known as &nbsp; ''pop count'', &nbsp; ''popcount'', &nbsp; ''sideways sum'', &nbsp; and &nbsp; ''Hamming weight''.
 
: For example,The &nbsp; <big>''[[wp:Hamming weight|population count]]'5'''</big> &nbsp; (which is the number of &nbsp; <big>'''1011'''</big>s &nbsp; in binary(ones) &nbsp; hasin athe populationbinary countrepresentation of &nbsp;a <big>'''2'''</big>non-negative integer.
 
''Population count'' &nbsp; is also known as:
::::* &nbsp; ''pop count''
::::* &nbsp; ''popcount''
::::* &nbsp; ''sideways sum''
::::* &nbsp; ''bit summation''
::::* &nbsp; ''Hamming weight''
 
 
For example, &nbsp; <big>'''5'''</big> &nbsp; (which is &nbsp; <big>'''101'''</big> &nbsp; in binary) &nbsp; has a population count of &nbsp; <big>'''2'''</big>.
 
 
Line 22 ⟶ 31:
 
;See also
* The On-Line Encyclopedia of Integer Sequences: &nbsp; [http[oeis://oeis.org/A000069 A000069A000120|A000120 odiouspopulation numberscount]].
* The On-Line Encyclopedia of Integer Sequences: &nbsp; [http[oeis://oeis.org/A001969 A001969A000069|A000069 evilodious numbers]].
* The On-Line Encyclopedia of Integer Sequences: &nbsp; [[oeis:A001969|A001969 evil numbers]].
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">print((0.<30).map(i -> bits:popcount(Int64(3) ^ i)))
 
[Int] evil, odious
V i = 0
L evil.len < 30 | odious.len < 30
V p = bits:popcount(i)
I (p % 2) != 0
odious.append(i)
E
evil.append(i)
i++
 
print(evil[0.<30])
print(odious[0.<30])</syntaxhighlight>
 
{{out}}
<pre>
[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
[0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]
[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]
</pre>
 
=={{header|360 Assembly}}==
Line 32 ⟶ 67:
* in Unnormalized Double Floating Point, one is implemented X'4E00000000000001'
<br>
<langsyntaxhighlight lang="360asm">* Population count 09/05/2019
POPCNT CSECT
USING POPCNT,R13 base register
Line 113 ⟶ 148:
CC DS C
REGEQU
END POPCNT </langsyntaxhighlight>
{{out}}
<pre>
Line 120 ⟶ 155:
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|8080 Assembly}}==
 
This program uses the parity flag to test whether a number is evil or odious,
and is therefore not compatible with the Z80, which reused that flag as an overflow flag.
It will only run correctly on a real 8080.
 
<syntaxhighlight lang="8080asm"> org 100h
mvi e,30 ; 3^0 to 3^29 inclusive
powers: push d ; Keep counter
;;; Calculate Hamming weight of pow3
lxi b,6 ; C = 6 bytes, B = counter
lxi h,pow3
ham48: mov a,m ; Get byte
ana a ; Clear carry
hambt: ral ; Rotate into carry
jnc $+4 ; Increment counter if carry set
inr b
ana a ; Done yet?
jnz hambt ; If not, keep going
dcr c ; More bytes?
inx h
jnz ham48 ; If not, keep going
mov a,b ; Print result
call outa
;;; Multiply pow3 by 3
mvi b,6 ; Make copy
lxi h,pow3
lxi d,pow3c
copy: mov a,m
stax d
inx h
inx d
dcr b
jnz copy
;;; Multiply by 3 (add copy to it twice)
lxi h,pow3c
lxi d,pow3
call add48
call add48
pop d ; Restore counter
dcr e ; Count down from 30
jnz powers
call outnl
;;; Print first 30 evil numbers
;;; An evil number has even parity
lxi b,-226 ; B=current number (start -1), C=counter
evil: inr b ; Increment number
jpo evil ; If odious, try next number
push b ; Otherwise, output it,
mov a,b
call outa
pop b
dcr c ; Decrement counter
jnz evil ; If not zero, get more numbers
call outnl
;;; Print first 30 odious numbers
;;; An odious number has odd parity
lxi b,-226
odious: inr b
jpe odious ; If number is evil, try next number
push b
mov a,b
call outa
pop b
dcr c
jnz odious
;;; Print newline
outnl: lxi d,nl
mvi c,9
jmp 5
;;; Print 2-digit number in A
outa: lxi d,0A2Fh ; D=10, E=high digit
mkdgt: inr e
sub d
jnc mkdgt
adi '0'+10 ; Low digit
push psw ; Save low digit
mvi c,2 ; Print high digit
call 5
pop psw ; Restore low digit
mov e,a ; Print low digit
mvi c,2
call 5
mvi e,' ' ; Print space
mvi c,2
jmp 5
;;; Add 48-byte number at [HL] to [DE]
add48: push h ; Keep pointers
push d
mvi b,6 ; 6 bytes
ana a ; Clear carry
a48l: ldax d ; Get byte at [DE]
adc m ; Add byte at [HL]
stax d ; Store result at [DE]
inx h ; Increment pointers
inx d
dcr b ; Any more bytes left?
jnz a48l ; If so, do next byte
pop d ; Restore pointers
pop h
ret
nl: db 13,10,'$'
pow3: db 1,0,0,0,0,0 ; pow3, starts at 1
pow3c: equ $ ; room for copy</syntaxhighlight>
 
{{out}}
<pre>01 02 02 04 03 06 06 05 06 08 09 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
00 03 05 06 09 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
01 02 04 07 08 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
 
=={{header|8086 Assembly}}==
 
<syntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
section .text
;;; Calculate hamming weights of 3^0 to 3^29.
;;; 3^29 needs a 48-bit representation, which
;;; we'll put in BP:SI:DI.
xor bp,bp ; BP:SI:DI = 1
xor si,si
xor di,di
inc di
mov cx,30
;;; Calculate pop count of BP:SI:DI
pow3s: push bp ; Keep state
push si
push di
xor ax,ax ; AL = counter
ham48: rcl bp,1
rcl si,1
rcl di,1
adc al,ah
mov dx,bp
or dx,si
or dx,di
jnz ham48
pop di ; Restore state
pop si
pop bp
call outal ; Output
;;; Multiply by 3
push bp ; Keep state
push si
push di
add di,di ; Mul by two (add to itself)
adc si,si
adc bp,bp
pop ax ; Add original (making x3)
add di,ax
pop ax
adc si,ax
pop ax
adc bp,ax
loop pow3s
call outnl
;;; Print first 30 evil numbers
;;; This is much easier, since they fit in a byte,
;;; and we only need to know whether the Hamming weight
;;; is odd or even, which is the same as the built-in
;;; parity check
mov cl,30
xor bx,bx
dec bx
evil: inc bx ; Increment number to test
jpo .next ; If parity is odd, number is not evil
mov al,bl ; Otherwise, output the number
call outal
dec cx ; One fewer left
.next: test cx,cx
jnz evil ; Next evil number
call outnl
;;; For the odious numbers it is the same
mov cl,30
xor bx,bx
dec bx
odious: inc bx
jpe .next ; Except this time we skip the evil numbers
mov al,bl
call outal
dec cx
.next: test cx,cx
jnz odious
;;; Print newline
outnl: mov ah,2
mov dl,13
int 21h
mov dl,10
int 21h
ret
;;; Print 2-digit number in AL
outal: aam
add ax,3030h
xchg dx,ax
xchg dl,dh
mov ah,2
int 21h
xchg dl,dh
int 21h
mov dl,' '
int 21h
ret</syntaxhighlight>
 
{{out}}
 
<pre>01 02 02 04 03 06 06 05 06 08 09 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
00 03 05 06 09 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
01 02 04 07 08 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO RETURN popcount n:
IF n=0: RETURN 0
RETURN (n mod 2) + popcount (floor (n/2))
 
HOW TO REPORT evil n:
REPORT (popcount n) mod 2 = 0
 
HOW TO REPORT odious n:
REPORT (popcount n) mod 2 = 1
 
FOR i IN {0..29}: WRITE popcount (3 ** i)
WRITE /
 
PUT {} IN evilnums
PUT {} IN odiousnums
 
FOR n IN {0..59}:
SELECT:
evil n: INSERT n IN evilnums
odious n: INSERT n IN odiousnums
 
FOR i IN {1..30}: WRITE evilnums item i
WRITE /
FOR i IN {1..30}: WRITE odiousnums item i
WRITE /</syntaxhighlight>
{{out}}
<pre>1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|Ada}}==
Line 125 ⟶ 401:
Specification and implementation of an auxiliary package "Population_Count". The same package is used for [[Pernicious numbers#Ada]]
 
<langsyntaxhighlight lang="ada">with Interfaces;
 
package Population_Count is
subtype Num is Interfaces.Unsigned_64;
function Pop_Count(N: Num) return Natural;
end Population_Count;</langsyntaxhighlight>
 
<langsyntaxhighlight Adalang="ada">package body Population_Count is
function Pop_Count(N: Num) return Natural is
Line 149 ⟶ 425:
end Pop_Count;
end Population_Count;</langsyntaxhighlight>
 
The main program:
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Population_Count; use Ada.Text_IO; use Population_Count;
 
procedure Test_Pop_Count is
Line 189 ⟶ 465:
end loop;
New_Line;
end Test_Pop_Count;</langsyntaxhighlight>
 
{{out}}
Line 198 ⟶ 474:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># returns the population count (number of bits on) of the non-negative #
# integer n #
PROC population count = ( LONG INT n )INT:
Line 239 ⟶ 515:
OD;
print( ( newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 248 ⟶ 524:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% returns the population count (number of bits on) of the non-negative integer n %
integer procedure populationCount( integer value n ) ;
Line 316 ⟶ 592:
end odious_numbers_loop
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 323 ⟶ 599:
odious numbers: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
APL (DYALOG APL)
popDemo←{⎕IO←0
N←⍵
⍝ popCount: Does a popCount of integers (8-32 bits) or floats (64-bits) that can be represented as integers
popCount←{
i2bits←{∊+/2⊥⍣¯1⊣⍵} ⍝ Use ⊥⍣¯1 (inverted decode) for ⊤ (encode) to automatically detect nubits needed
+/i2bits ⍵ ⍝ Count the bits
 
act3←popCount 3*⍳N
 
M←N×2
actEvil←N↑{⍵/⍨0=2|popCount ⍵}⍳M
actOdious←N↑{⍵/⍨1=2|popCount ⍵}⍳M
 
⎕←'powers 3'act3
⎕←'evil 'actEvil
⎕←'odious 'actOdious
 
⍝ Extra: Validate answers are correct
⍝ Actual answers
ans3←1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
ansEvil←0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
ansOdious←1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
 
'***Passes' '***Fails'⊃⍨(ans3≢act3)∨(actEvil≢ansEvil)∨(actOdious≢ansOdious)
}
</syntaxhighlight>
{{out}}
popDemo 30
powers 3 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
***Passes
 
=={{header|AppleScript}}==
===Functional===
 
{{Trans|JavaScript}}
<syntaxhighlight lang="applescript">--------------------- POPULATION COUNT ---------------------
<lang AppleScript>-- popCount :: Int -> Int
 
on popCount(n)
-- populationCount :: Int -> Int
script bitSum
on populationCount(n)
on |λ|(a, x)
-- The number of non-zero bits in the binary
a + (x as integer)
-- representation of the integer n.
script go
on |λ|(x)
if 0 < x then
Just({x mod 2, x div 2})
else
Nothing()
end if
end |λ|
end script
integerSum(unfoldr(go, n))
foldl(bitSum, 0, characters of showIntAtBase(n, 2))
end popCountpopulationCount
 
 
-- TEST -------------------------------------------- TEST ---------------------------
on run
set {evens, odds} to partition(compose(even, populationCount), ¬
script powerOfThreePopCount
on |λ|enumFromTo(x0, 59))
popCount(3 ^ x)
end |λ|
end script
unlines({"Population counts of the first 30 powers of three:", ¬
script popCountisEven
tab & showList(map(compose(populationCount, raise(3)), ¬
enumFromTo(0, 29))), ¬
"", ¬
"First thirty 'evil' numbers:", ¬
tab & showList(evens), ¬
"", ¬
"First thirty 'odious' numbers:", ¬
tab & showList(odds)})
end run
 
 
------------------------- GENERIC --------------------------
 
-- Just :: a -> Maybe a
on Just(x)
-- Constructor for an inhabited Maybe (option type) value.
-- Wrapper containing the result of a computation.
{type:"Maybe", Nothing:false, Just:x}
end Just
 
 
-- Nothing :: Maybe a
on Nothing()
-- Constructor for an empty Maybe (option type) value.
-- Empty wrapper returned where a computation is not possible.
{type:"Maybe", Nothing:true}
end Nothing
 
 
-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
on compose(f, g)
script
property mf : mReturn(f)
property mg : mReturn(g)
on |λ|(x)
popCountmf's |λ|(mg's |λ|(x) mod 2 = 0)
end |λ|
end script
end compose
{popCounts:¬
map(powerOfThreePopCount, enumFromTo(0, 30)), evenThenOdd:¬
partition(popCountisEven, enumFromTo(0, 59))}
end run
 
 
-- GENERIC FUNCTIONS ----------------------------------------------------------
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set dlst to -1{}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
set d to 1{}
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
 
 
-- even :: Int -> Bool
on even(x)
0 = x mod 2
end even
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 385 ⟶ 740:
end tell
end foldl
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
Line 398 ⟶ 756:
end map
 
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: HandlerFirst-class m => (a -> b) -> m (a -> Scriptb)
on mReturn(f)
if-- 2nd class ofhandler ffunction islifted into 1st class script thenwrapper.
if script is class of f then
f
else
Line 410 ⟶ 769:
end mReturn
 
-- partition :: predicate -> List -> (Matches, nonMatches)
-- partition :: (a -> Bool) -> [a] -> ([a], [a])
on partition(f, xs)
tell mReturn(f)
set lstys to {{}, {}}
set zs to {}
repeat with x in xs
set v to contents of x
setif end of item ((|λ|(v) as integer) + 1) of lst to vthen
set end of ys to v
else
set end of zs to v
end if
end repeat
end tell
{item 2 of lstys, item 1 of lstzs}
end partition
 
-- showIntAtBaseraise :: IntNum -> Int -> StringNum
on raise(m)
on showIntAtBase(n, base)
script
if base > 1 then
ifon |λ|(n > 0 then)
set m to^ n mod base
end set r to n - m|λ|
end script
if r > 0 then
end raise
set prefix to showIntAtBase(r div base, base)
 
else
 
set prefix to ""
-- integerSum :: [Num] -> Num
on integerSum(xs)
script addInt
on |λ|(a, b)
a + (b as integer)
end |λ|
end script
foldl(addInt, 0, xs)
end integerSum
 
 
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end intercalate
 
 
-- showList :: [a] -> String
on showList(xs)
"[" & intercalate(",", map(my str, xs)) & "]"
end showList
 
 
-- str :: a -> String
on str(x)
x as string
end str
 
 
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
-- A list derived from a simple value.
-- Dual to foldr.
-- unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
-- -> [10,9,8,7,6,5,4,3,2,1]
set xr to {v, v} -- (value, remainder)
set xs to {}
tell mReturn(f)
repeat -- Function applied to remainder.
set mb to |λ|(item 2 of xr)
if Nothing of mb then
exit repeat
else -- New (value, remainder) tuple,
set xr to Just of mb
-- and value appended to output list.
set end of xs to item 1 of xr
end if
end repeat
end tell
if m < 10 then
return xs
set baseCode to 48 -- "0"
end unfoldr
else
 
set baseCode to 55 -- "A" - 10
 
end if
-- unlines :: [String] -> String
on unlines(xs)
prefix & character id (baseCode + m)
-- A single string formed by the intercalation
else
-- of a list of strings with the "0"newline character.
set {dlm, my text enditem ifdelimiters} to ¬
{my text item delimiters, linefeed}
else
set s to xs missingas valuetext
set my text item delimiters to dlm
end if
s
end showIntAtBase</lang>
end unlines</syntaxhighlight>
{{Out}}
<pre>Population counts of the first 30 powers of three:
<lang AppleScript>{popCounts:
{ [1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25, 25}, ]
 
evenThenOdd:
First thirty 'evil' numbers:
{{0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58},
{1, 2, 4, 7, 8[0, 113, 135, 146, 169, 1910, 2112, 2215, 2517, 2618, 2820, 3123, 3224, 3527, 3729, 3830, 4133, 4234, 4436, 4739, 4940, 5043, 5245, 5546, 5648, 59}}}</lang>51,53,54,57,58]
 
First thirty 'odious' numbers:
[1,2,4,7,8,11,13,14,16,19,21,22,25,26,28,31,32,35,37,38,41,42,44,47,49,50,52,55,56,59]</pre>
 
----
===Straightforward===
 
<syntaxhighlight lang="applescript">on popCount(n)
set counter to 0
repeat until (n is 0)
set counter to counter + n mod 2
set n to n div 2
end repeat
return counter div 1
end popCount
 
-- Task code:
-- Get the popcounts of the first 30 powers of 3.
set list1 to {}
repeat with i from 0 to 29
set end of list1 to popCount(3 ^ i)
end repeat
 
-- Collate the integers from 0 to 59 according to the evenness or oddness of their popcounts.
-- In any even number of consecutive integers, exactly half are "evil" and half "odious". Thus thirty of each here.
set lists2and3 to {{}, {}}
repeat with i from 0 to 59
set end of item (popCount(i) mod 2 + 1) of lists2and3 to i
end repeat
 
-- Arrange the results for display.
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to space
set {list1, list2, list3} to {list1 as text, beginning of lists2and3 as text, end of lists2and3 as text}
set AppleScript's text item delimiters to linefeed
set output to {"Popcounts of 1st thirty powers of 3:", list1, "1st thirty evil numbers:", list2, "1st thirty odious numbers:", list3} ¬
as text
set AppleScript's text item delimiters to astid
return output</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"Popcounts of 1st thirty powers of 3:
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
1st thirty evil numbers:
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1st thirty odious numbers:
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59"</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">popCount: function [num][
size select split to :string as.binary num 'x -> x="1"
]
 
print "population count for the first thirty powers of 3:"
print map 0..29 => [popCount 3^&]
 
print "first thirty evil numbers"
print take select 0..100 => [even? popCount &] 30
 
print "first thirty odious numbers"
print take select 0..100 => [odd? popCount &] 30</syntaxhighlight>
 
{{out}}
 
<pre>population count for the first thirty powers of 3:
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
first thirty evil numbers
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
first thirty odious numbers
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, 30
Out1 .= PopCount(3 ** (A_Index - 1)) " "
Loop, 60
Line 469 ⟶ 955:
, x := (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
return (x * 0x0101010101010101) >> 56
}</langsyntaxhighlight>
{{Output}}
<pre>3^x: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59 </pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f POPULATION_COUNT.AWK
# converted from VBSCRIPT
BEGIN {
nmax = 30
b = 3
n = 0
bb = 1
for (i=1; i<=nmax; i++) {
list = list pop_count(bb) " "
bb *= b
}
printf("%s^n: %s\n",b,list)
for (j=0; j<=1; j++) {
c = (j == 0) ? "evil" : "odious"
i = n = 0
list = ""
while (n < nmax) {
if (pop_count(i) % 2 == j) {
n++
list = list i " "
}
i++
}
printf("%s: %s\n",c,list)
}
exit(0)
}
function pop_count(xx, xq,xr,y) {
while (xx > 0) {
xq = int(xx / 2)
xr = xx - xq * 2
if (xr == 1) { y++ }
xx = xq
}
return(y)
}
</syntaxhighlight>
{{out}}
<pre>
3^n: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|Yabasic}}
<syntaxhighlight lang="basic256">print "Pop cont (3^x): ";
for i = 0 to 29
print population(3^i); " "; #los últimos números no los muestra correctamente
next i
 
print : print
print "Evil numbers: ";
call EvilOdious(30, 0)
 
print : print
print "Odious numbers: ";
call EvilOdious(30, 1)
end
 
subroutine EvilOdious(limit, type)
i = 0 : cont = 0
 
do
eo = (population(i) mod 2)
if (type and eo) or (not type and not eo) then
cont += 1 : print i; " ";
end if
i += 1
until (cont = limit)
end subroutine
 
function population(number)
popul = 0
 
binary$ = tobinary(number)
for i = 1 to length(binary$)
popul += int(mid(binary$, i, 1))
next i
return popul
end function</syntaxhighlight>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="vb">function tobin$(num)
bin$ = ""
if num = 0 then bin$ = "0"
while num >= 1
num = num / 2
X$ = str$(num)
D$ = "": F$ = ""
for i = 1 to len(X$)
L$ = mid$(X$, i, 1)
if L$ <> "." then
D$ = D$ + L$
else
F$ = F$ + right$(X$, len(X$) - i)
exit for
end if
next i
if F$ = "" then B$ = "0" else B$ = "1"
bin$ = bin$ + B$
num = val(D$)
wend
B$ = ""
for i = len(bin$) to 1 step -1
B$ = B$ + mid$(bin$, i, 1)
next i
tobin$ = B$
end function
 
function population(number)
popul = 0
'digito$ = tobin$(number)
'print tobin$(number)
for i = 1 to len(tobin$(number))
popul = popul + val(mid$(tobin$(number), i, 1))
next i
population = popul
end function
 
sub evilodious limit, tipo
i = 0
cont = 0
while 1
eo = (population(i) mod 2)
if (tipo and eo = 1) or ((not(tipo) and not(eo)) = 1) then
cont = cont + 1: print i; " ";
end if
i = i + 1
if cont = limit then exit while
wend
end sub
 
print "Pop cont (3^x): ";
for i = 0 to 14
print population(3 ^ i); " ";
next i
 
print
print "Evil numbers: ";
call evilodious 15, 0
 
print
print "Odious numbers: ";
call evilodious 15, 1
end</syntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
// Definitions
let popcount(n) = n=0 -> 0, (n&1) + popcount(n >> 1)
let evil(n) = (popcount(n) & 1) = 0
let odious(n) = (popcount(n) & 1) = 1
 
// The BCPL word size is implementation-dependent,
// but very unlikely to be big enough to store 3^29.
// This implements a 48-bit integer using byte strings.
let move48(dest, src) be
for i=0 to 5 do dest%i := src%i
 
let set48(dest, n) be
for i=5 to 0 by -1
$( dest%i := n & #XFF
n := n >> 8
$)
let add48(dest, src) be
$( let temp = ? and carry = 0
for i=5 to 0 by -1
$( temp := dest%i + src%i + carry
carry := temp > #XFF -> 1, 0
dest%i := temp & #XFF
$)
$)
 
let mul3(n) be
$( let temp = vec 2 // big enough even on a 16-bit machine
move48(temp, n)
add48(n, n)
add48(n, temp)
$)
 
let popcount48(n) = valof
$( let total = 0
for i=0 to 5 do
total := total + popcount(n%i)
resultis total
$)
 
// print the first N numbers
let printFirst(amt, prec) be
$( let seen = 0 and n = 0
until seen >= amt
$( if prec(n)
$( writed(n, 3)
seen := seen + 1
$)
n := n + 1
$)
wrch('*N')
$)
 
let start() be
$( let pow3 = vec 2
// print 3^0 to 3^29
set48(pow3, 1)
for i = 0 to 29
$( writed(popcount48(pow3), 3)
mul3(pow3)
$)
wrch('*N')
// print the first 30 evil and odious numbers
printFirst(30, evil)
printFirst(30, odious)
$)</syntaxhighlight>
{{out}}
<pre> 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">PopCount ← {(2|𝕩)+𝕊⍟×⌊𝕩÷2}
Odious ← 2|PopCount
Evil ← ¬Odious
 
_List ← {𝕩↑𝔽¨⊸/↕2×𝕩}
>⟨PopCount¨ 3⋆↕30,
Evil _List 30,
Odious _List 30⟩</syntaxhighlight>
{{out}}
<pre>┌─
╵ 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
┘</pre>
 
=={{header|C}}==
{{works with|GCC}}
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main() {
Line 515 ⟶ 1,247:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 525 ⟶ 1,257:
 
GCC's builtin doesn't exist prior to 3.4, and the LL version is broken in 3.4 to 4.1. In 4.2+, if the platform doesn't have a good popcount instruction or isn't enabled (e.g. not compiled with <code>-march=native</code>), it typically emits unoptimized code which is over 2x slower than the C below. Alternative:
<langsyntaxhighlight lang="c">#if defined(__POPCNT__) && defined(__GNUC__) && (__GNUC__> 4 || (__GNUC__== 4 && __GNUC_MINOR__> 1))
#define HAVE_BUILTIN_POPCOUNTLL
#endif
Line 540 ⟶ 1,272:
b = (b + (b >> 4)) & 0x0f0f0f0f;
return (b * 0x01010101) >> 24;
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|C++11}}
<lang cpp>#include <iostream>
#include <bitset>
#include <climits>
 
size_t popcount(unsigned long long n) {
return std::bitset<CHAR_BIT * sizeof n>(n).count();
}
 
int main() {
{
unsigned long long n = 1;
for (int i = 0; i < 30; i++) {
std::cout << popcount(n) << " ";
n *= 3;
}
std::cout << std::endl;
}
 
int od[30];
int ne = 0, no = 0;
std::cout << "evil : ";
for (int n = 0; ne+no < 60; n++) {
if ((popcount(n) & 1) == 0) {
if (ne < 30) {
std::cout << n << " ";
ne++;
}
} else {
if (no < 30) {
od[no++] = n;
}
}
}
std::cout << std::endl;
std::cout << "odious: ";
for (int i = 0; i < 30; i++) {
std::cout << od[i] << " ";
}
std::cout << std::endl;
 
return 0;
}</lang>
{{out}}
<pre>
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Linq;
Line 665 ⟶ 1,346:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 673 ⟶ 1,354:
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|C++}}==
{{works with|C++11}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <bitset>
#include <climits>
 
size_t popcount(unsigned long long n) {
return std::bitset<CHAR_BIT * sizeof n>(n).count();
}
 
int main() {
{
unsigned long long n = 1;
for (int i = 0; i < 30; i++) {
std::cout << popcount(n) << " ";
n *= 3;
}
std::cout << std::endl;
}
 
int od[30];
int ne = 0, no = 0;
std::cout << "evil : ";
for (int n = 0; ne+no < 60; n++) {
if ((popcount(n) & 1) == 0) {
if (ne < 30) {
std::cout << n << " ";
ne++;
}
} else {
if (no < 30) {
od[no++] = n;
}
}
}
std::cout << std::endl;
std::cout << "odious: ";
for (int i = 0; i < 30; i++) {
std::cout << od[i] << " ";
}
std::cout << std::endl;
 
return 0;
}</syntaxhighlight>
{{out}}
<pre>
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn population-count [n]
(Long/bitCount n)) ; use Java inter-op
 
(defn exp [n pow]
(reduce * (repeat pow n)))
 
(defn evil? [n]
(even? (population-count n)))
 
(defn odious? [n]
(odd? (population-count n)))
 
;;
;; Clojure's support for generating "lazily-evaluated" infinite sequences can
;; be used to generate the requested output sets. We'll create some infinite
;; sequences, and only as many items will be computed as are "pulled" by 'take'.
;;
(defn integers []
(iterate inc 0))
 
(defn powers-of-n [n]
(map #(exp n %) (integers)))
 
(defn evil-numbers []
(filter evil? (integers)))
 
(defn odious-numbers []
(filter odious? (integers)))</syntaxhighlight>
 
{{out}}
<pre>
(take 5 (integers)) ; ==> (0 1 2 3 4)
(take 5 (powers-of-n 3)) ; ==> (1 3 9 27 81)
(take 5 (evil-numbers)) ; ==> (0 3 5 6 9)
 
;; Population Counts for first 30 powers of 3:
(take 30 (map population-count (powers-of-n 3)))
; ==> (1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25)
 
;; First 30 'evil' numbers:
(take 30 (evil-numbers))
; ==> (0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58)
 
;; First 30 'odious' numbers:
(take 30 (odious-numbers))
; ==> (1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59)
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">pop_count = proc (n: int) returns (int)
p: int := 0
while n>0 do
p := p + n//2
n := n/2
end
return(p)
end pop_count
 
evil = proc (n: int) returns (bool)
return(pop_count(n)//2 = 0)
end evil
 
odious = proc (n: int) returns (bool)
return(~evil(n))
end odious
 
first = iter (n: int, p: proctype (int) returns (bool)) yields (int)
i: int := 0
while n>0 do
if p(i) then
yield(i)
n := n-1
end
i := i+1
end
end first
 
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(0,29) do
stream$putright(po, int$unparse(pop_count(3**i)), 3)
end
stream$putl(po, "")
for i: int in first(30, evil) do
stream$putright(po, int$unparse(i), 3)
end
stream$putl(po, "")
for i: int in first(30, odious) do
stream$putright(po, int$unparse(i), 3)
end
stream$putl(po, "")
end start_up</syntaxhighlight>
{{out}}
<pre> 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. HAMMING.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 POPCOUNT-VARIABLES.
03 POPCOUNT-IN PIC 9(15)V9.
03 FILLER REDEFINES POPCOUNT-IN.
05 POPCOUNT-REST PIC 9(15).
05 FILLER PIC 9.
88 BIT-IS-SET VALUE 5.
03 POPCOUNT-OUT PIC 99.
03 FILLER REDEFINES POPCOUNT-OUT.
05 FILLER PIC 9.
05 FILLER PIC 9.
88 EVIL VALUES 0, 2, 4, 6, 8.
88 ODIOUS VALUES 1, 3, 5, 7, 9.
 
01 STATE-VARIABLES.
03 CUR-POWER-3 PIC 9(15) VALUE 1.
03 CUR-EVIL-NUM PIC 99 VALUE 0.
03 CUR-ODIOUS-NUM PIC 99 VALUE 0.
03 LINE-INDEX PIC 99 VALUE 1.
 
01 OUTPUT-FORMAT.
03 LINENO PIC Z9.
03 FILLER PIC X VALUE '.'.
03 FILLER PIC XX VALUE SPACES.
03 OUT-POW3 PIC Z9.
03 FILLER PIC X(4) VALUE SPACES.
03 OUT-EVIL PIC Z9.
03 FILLER PIC X(4) VALUE SPACES.
03 OUT-ODIOUS PIC Z9.
 
PROCEDURE DIVISION.
BEGIN.
DISPLAY " 3^ EVIL ODD"
PERFORM MAKE-LINE 30 TIMES.
STOP RUN.
MAKE-LINE.
MOVE LINE-INDEX TO LINENO.
MOVE CUR-POWER-3 TO POPCOUNT-IN.
PERFORM FIND-POPCOUNT.
MOVE POPCOUNT-OUT TO OUT-POW3.
PERFORM FIND-EVIL.
MOVE CUR-EVIL-NUM TO OUT-EVIL.
PERFORM FIND-ODIOUS.
MOVE CUR-ODIOUS-NUM TO OUT-ODIOUS.
DISPLAY OUTPUT-FORMAT.
MULTIPLY 3 BY CUR-POWER-3.
ADD 1 TO CUR-EVIL-NUM.
ADD 1 TO CUR-ODIOUS-NUM.
ADD 1 TO LINE-INDEX.
FIND-EVIL.
MOVE CUR-EVIL-NUM TO POPCOUNT-IN.
PERFORM FIND-POPCOUNT.
IF NOT EVIL, ADD 1 TO CUR-EVIL-NUM, GO TO FIND-EVIL.
 
FIND-ODIOUS.
MOVE CUR-ODIOUS-NUM TO POPCOUNT-IN.
PERFORM FIND-POPCOUNT.
IF NOT ODIOUS, ADD 1 TO CUR-ODIOUS-NUM, GO TO FIND-ODIOUS.
FIND-POPCOUNT.
MOVE 0 TO POPCOUNT-OUT.
PERFORM PROCESS-BIT UNTIL POPCOUNT-IN IS EQUAL TO ZERO.
 
PROCESS-BIT.
DIVIDE 2 INTO POPCOUNT-IN.
IF BIT-IS-SET, ADD 1 TO POPCOUNT-OUT.
MOVE POPCOUNT-REST TO POPCOUNT-IN.</syntaxhighlight>
{{out}}
<pre> 3^ EVIL ODD
1. 1 0 1
2. 2 3 2
3. 2 5 4
4. 4 6 7
5. 3 9 8
6. 6 10 11
7. 6 12 13
8. 5 15 14
9. 6 17 16
10. 8 18 19
11. 9 20 21
12. 13 23 22
13. 10 24 25
14. 11 27 26
15. 14 29 28
16. 15 30 31
17. 11 33 32
18. 14 34 35
19. 14 36 37
20. 17 39 38
21. 17 40 41
22. 20 43 42
23. 19 45 44
24. 22 46 47
25. 16 48 49
26. 18 51 50
27. 24 53 52
28. 30 54 55
29. 25 57 56
30. 25 58 59</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(format T "3^x: ~{~a ~}~%"
(loop for i below 30
collect (logcount (expt 3 i))))
Line 686 ⟶ 1,628:
finally (return (values evil odious)))
(format T "evil: ~{~a ~}~%" evil)
(format T "odious: ~{~a ~}~%" odious))</langsyntaxhighlight>
{{Out}}
<pre>3^x: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
For Crystal select|reject are inherently lazy enumerators, and has popcount for upto unsigned 64-bit integers.
<syntaxhighlight lang="ruby">struct Int
def evil?
self >= 0 && popcount.even?
end
end
puts "Powers of 3:", (0...30).map{|n| (3u64 ** n).popcount}.join(' ') # can also use &** (to prevent arithmetic overflow)
puts "Evil:" , 0.step.select(&.evil?).first(30).join(' ')
puts "Odious:", 0.step.reject(&.evil?).first(30).join(' ')</syntaxhighlight>
{{Out}}<pre>Powers of 3:
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil:
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious:
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, core.bitop;
 
Line 701 ⟶ 1,663:
uint.max.iota.filter!(i => pCount(i) % 2 == 0).take(30),
uint.max.iota.filter!(i => pCount(i) % 2).take(30));
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
Evil: [0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]
Odious: [1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils, Math}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Population_count;
 
{$APPTYPE CONSOLE}
 
{$R *.res}
 
uses
System.SysUtils,
Math;
 
function PopulationCount(AInt: UInt64): Integer;
begin
Result := 0;
repeat
inc(Result, (AInt and 1));
AInt := AInt div 2;
until (AInt = 0);
end;
 
var
i, count: Integer;
n: Double;
popCount: Integer;
 
begin
Writeln('Population Counts:'#10);
Write('3^n : ');
for i := 0 to 30 do
begin
n := Math.Power(3, i);
popCount := PopulationCount(round(n));
Write(Format('%d ', [popCount]));
end;
Writeln(#10#10'Evil: ');
 
count := 0;
i := 0;
while (count < 30) do
begin
popCount := PopulationCount(i);
if not Odd(popCount) then
begin
inc(count);
Write(Format('%d ', [i]));
end;
inc(i);
end;
Writeln(#10#10'Odious: ');
 
count := 0;
i := 0;
while (count < 30) do
begin
popCount := PopulationCount(i);
if Odd(popCount) then
begin
inc(count);
Write(Format('%d ', [i]));
end;
inc(i);
end;
 
readln;
end.
 
</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func popcnt x .
while x > 0
r += x mod 2
x = x div 2
.
return r
.
proc show3 . .
write "3^n:"
bb = 1
for i = 1 to 30
write " " & popcnt bb
bb *= 3
.
print ""
.
proc show s$ x . .
write s$
while n < 30
if popcnt i mod 2 = x
n += 1
write " " & i
.
i += 1
.
print ""
.
show3
show "evil:" 0
show "odious:" 1
</syntaxhighlight>
 
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Population do
 
def count(n), do: count(<<n :: integer>>, 0)
Line 727 ⟶ 1,795:
IO.inspect Stream.iterate(0, &(&1+1)) |> Stream.filter(&Population.evil?(&1)) |> Enum.take(30)
IO.puts "first thirty odious numbers:"
IO.inspect Stream.iterate(0, &(&1+1)) |> Stream.filter(&Population.odious?(&1)) |> Enum.take(30)</langsyntaxhighlight>
 
{{out}}
Line 740 ⟶ 1,808:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(population_count).
-export([popcount/1]).
 
Line 789 ⟶ 1,857:
io:format("Powers of 3: ~p~n",[threes(30)]),
io:format("Evil:~p~n",[evil(30)]),
io:format("Odious:~p~n",[odious(30)]).</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="erlang">61> population_count:task().
Powers of 3: [1,2,2,4,3,6,6,5,6,8,9,13,10,11,14,15,11,14,14,17,17,20,19,22,16,18,24,30,25,
25]
Line 798 ⟶ 1,866:
Odious:[1,2,4,7,8,11,13,14,16,19,21,22,25,26,28,31,32,35,37,38,41,42,44,47,49,
50,52,55,56,59]
ok</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Population count. Nigel Galloway: February 18th., 2021
let pC n=Seq.unfold(fun n->match n/2L,n%2L with (0L,0L)->None |(n,g)->Some(g,n))n|>Seq.sum
printf "pow3 :"; [0..29]|>List.iter((pown 3L)>>pC>>(printf "%3d")); printfn ""
printf "evil :"; Seq.initInfinite(int64)|>Seq.filter(fun n->(pC n) &&& 1L=0L)|>Seq.take 30|>Seq.iter(printf "%3d"); printfn ""
printf "odious:"; Seq.initInfinite(int64)|>Seq.filter(fun n->(pC n) &&& 1L=1L)|>Seq.take 30|>Seq.iter(printf "%3d"); printfn ""
</syntaxhighlight>
{{out}}
<pre>
pow3 : 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel lists lists.lazy math math.bitsbitwise
math.functions namespaces prettyprint.config sequences ;
IN: rosetta-code.population-count
 
: pop-count3^n ( nobj -- mobj' ) make-bits [ t3 =swap ]^ bit-count ] lmap-lazy ;
: 3^nevil ( obj -- obj' ) [ 3 swap ^ popbit-count even? ] lmap-lazylfilter ;
: evilodious ( obj -- obj' ) [ popbit-count evenodd? ] lfilter ;
: odious ( obj -- obj' ) [ pop-count odd? ] lfilter ;
 
100 margin set 0 lfrom [ 3^n ] [ evil ] [ odious ] tri
: pop-count-demo ( -- )
[ 30 swap ltake list>array ] tri@
100 margin set 0 lfrom [ 3^n ] [ evil ] [ odious ] tri
"3^n: %u\nEvil: %u\nOdious: %u\n" printf</syntaxhighlight>
[ 30 swap ltake list>array ] tri@
"3^n: %u\nEvil: %u\nOdious: %u\n" printf ;
 
MAIN: pop-count-demo</lang>
{{out}}
<pre>
Line 823 ⟶ 1,900:
</pre>
 
=={{header|FōrmulæFermat}}==
<syntaxhighlight lang="fermat">Func Popcount(n) = if n = 0 then 0 else if 2*(n\2)=n then Popcount(n\2) else Popcount((n-1)\2)+1 fi fi.
 
Func Odiousness(n) = p:=Popcount(n);if 2*(p\2) = p then 0 else 1 fi.
In [https://wiki.formulae.org/Population_count this] page you can see the solution of this task.
 
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
for n=0 to 29 do !Popcount(3^n);!' ' od
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
e:=0
n:=0
while e<30 do if Odiousness(n)=0 then !n;!' ';e:=e+1 fi; n:=n+1 od
e:=0
n:=0
while e<30 do if Odiousness(n)=1 then !n;!' ';e:=e+1 fi; n:=n+1 od</syntaxhighlight>
 
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<langsyntaxhighlight Forthlang="forth">: popcnt ( n -- u) 0 swap
BEGIN dup WHILE tuck 1 AND + swap 1 rshift REPEAT
DROP ;
Line 852 ⟶ 1,933:
over odious? IF over . 1+ THEN swap 1+ swap
REPEAT DROP DROP CR ;
task1 task2 task3 BYE</langsyntaxhighlight>
{{out}}
<pre>3**i popcnt: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Line 860 ⟶ 1,941:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program population_count
implicit none
 
Line 910 ⟶ 1,991:
 
end function
end program</langsyntaxhighlight>
{{out}}
<pre> 3**i : 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Line 920 ⟶ 2,001:
It accepts one integer parameter and is defined for all unsigned integer types.
Therefore its implementation is skipped.
<langsyntaxhighlight lang="pascal">program populationCount(input, output, stdErr);
var
// general advice: iterator variables are _signed_
Line 981 ⟶ 2,062:
end;
writeLn();
end.</langsyntaxhighlight>
{{out}}
<pre> 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Population_count}}
 
'''Solution'''
 
Fōrmulæ has an integrated expression BitCount that counts the number of 1's of the binary representation of the number.
 
However, a function can also be written, as follows:
 
[[File:Fōrmulæ - Population count 01.png]]
 
'''Case 1. Display the pop count of the 1st thirty powers of 3'''
 
[[File:Fōrmulæ - Population count 02.png]]
 
[[File:Fōrmulæ - Population count 03.png]]
 
'''Case 2. Display the 1st thirty evil numbers'''
 
We need first a function to calculate the first numbers whose population count satisfies a given condition, passed as a lambda expression:
 
[[File:Fōrmulæ - Population count 04.png]]
 
[[File:Fōrmulæ - Population count 05.png]]
 
[[File:Fōrmulæ - Population count 06.png]]
 
'''Case 3. Display the 1st thirty odious numbers'''
 
[[File:Fōrmulæ - Population count 07.png]]
 
[[File:Fōrmulæ - Population count 08.png]]
 
=={{Header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
#define NTERMS 30
 
function popcount( n as ulongint ) as uinteger
if n = 0 then return 0
if n = 1 then return 1
if n mod 2 = 0 then return popcount(n/2)
return 1 + popcount( (n - 1)/2 )
end function
 
dim as ulongint i=0, tp(0 to NTERMS-1), evil(0 to NTERMS-1),_
odious(0 to NTERMS-1), k, ne=0, no=0
 
while ne < NTERMS or no < NTERMS
if i<NTERMS then tp(i) = popcount(3^i)
k = popcount(i)
if k mod 2 = 0 and ne < NTERMS then
evil(ne) = i
ne += 1
endif
if k mod 2 = 1 and no < NTERMS then
odious(no) = i
no += 1
end if
i += 1
wend
 
dim as string s_tp = "", s_evil = "", s_odious = ""
 
for i = 0 to NTERMS-1
s_tp += str(tp(i))+" "
s_evil += str(evil(i))+" "
s_odious += str(odious(i))+" "
next i
 
print s_tp
print s_evil
print s_odious</syntaxhighlight>
{{out}}
<pre>
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
 
=={{Header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_limit = 30
 
local fn Population( x as long ) as long
long q, r, y = 0
while ( x > 0 )
q = int( x / 2 )
r = x - q * 2
if r == 1 then y++
x = q
wend
end fn = y
 
void local fn EvilOdious
long i = 0, k, ee = 0, eo = 0
long type(_limit - 1), evil(_limit - 1), odious(_limit - 1)
Str255 typeStr, evilStr, odiousStr
while ( ( ee < _limit ) or ( eo < _limit ) )
if i < _limit then type(i) = fn Population(3^i)
k = fn Population(i)
if k mod 2 == 0 and ee < _limit then evil(ee) = i : ee++
if k mod 2 == 1 and eo < _limit then odious(eo) = i : eo++
i++
wend
typeStr = "" : evilStr = "" : odiousStr = ""
for i = 0 to _limit - 1
typeStr = typeStr + str$( type(i) ) + " "
evilStr = evilStr + str$( evil(i) ) + " "
odiousStr = odiousStr + str$( odious(i) ) + " "
next
print typeStr : print evilStr : print odiousStr
end fn
 
fn EvilOdious
 
HandleEvent
</syntaxhighlight>
{{output}}
<pre>
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=538335b7b71f5ea7b59c0c82fbb0ea3e Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sEvil, sOdious As String 'To store the output for printing Evil and Odious
Dim iCount, iEvil, iOdious As Integer 'Counters
Line 1,016 ⟶ 2,227:
Print "1st 30 Odious numbers =\t" & sOdious 'Print Odious
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,027 ⟶ 2,238:
===Standard Library===
As of Go 1.9, this function is in the standard Library.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,064 ⟶ 2,275:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,076 ⟶ 2,287:
===Implementation===
Method of WP example '''popcount_3''':
<langsyntaxhighlight lang="go">func pop64(w uint64) int {
const (
ff = 1<<64 - 1
Line 1,088 ⟶ 2,299:
w = (w + w>>4) & maskf
return int(w * maskp >> 56)
}</langsyntaxhighlight>
Method of WP example '''popcount_4''':
<langsyntaxhighlight lang="go">func pop64(w uint64) (c int) {
for w != 0 {
w &= w - 1
Line 1,096 ⟶ 2,307:
}
return
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
{{works with|GHC|7.4+}}
<langsyntaxhighlight lang="haskell">import Data.Bits (popCount)
 
printPops :: (Show a, Integral a) => String -> [a] -> IO ()
Line 1,109 ⟶ 2,320:
printPops "popcount " $ map popCount $ iterate (*3) (1 :: Integer)
printPops "evil " $ filter (even . popCount) ([0..] :: [Integer])
printPops "odious " $ filter ( odd . popCount) ([0..] :: [Integer])</langsyntaxhighlight>
{{out}}
<pre>
Line 1,119 ⟶ 2,330:
Or, if we want to write our own popCount, perhaps something like:
 
<syntaxhighlight lang ="haskell">import Data.ListBifoldable (partition, unfoldrbiList)
import Data.BifoldableList (biListpartition, unfoldr)
import Data.Tuple (swap)
import Data.Bool (bool)
 
-- POPCOUNT ------------------------------------------ POPULATION COUNT -------------------
popCount :: Int -> Int
popCount = sum . unfoldr go
where
sum . unfoldr ((bool Nothing . Just . swap . flip quotRem 2) <*> (0 <))
go x
| 0 < x = (Just . swap) (quotRem x 2)
| otherwise = Nothing
 
-- TEST ---------------------------------------- TEST -------------------------
main :: IO ()
main =
mapM_ putStrLn $
zipWith
(\k xs -> kconcat ++[k, ":\n" ++, show xs ++, "\n"])
["Population count of powers of 3", "evil", "odious"]
( (popCount . (3 ^) <$> [0 .. 29]) :
biList (partition (even . popCount) [0 .. 59]))</lang>
)</syntaxhighlight>
{{Out}}
<pre>Population count of powers of 3:
Line 1,150 ⟶ 2,364:
=={{header|Idris}}==
 
<langsyntaxhighlight Idrislang="idris">module Main
import Data.Vect
 
Line 1,189 ⟶ 2,403:
printCompact (filterUnfoldN 30 isEvil id (1 +) 0)
putStr "Odious: "
printCompact (filterUnfoldN 30 isOdious id (1 +) 0)</langsyntaxhighlight>
{{Out}}
<pre>popcnt(3**i): 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Line 1,199 ⟶ 2,413:
Implementation:
 
<langsyntaxhighlight Jlang="j">countPopln=: +/"1@#:
isOdd=: 1 = 2&|
isEven=: 0 = 2&|</langsyntaxhighlight>
 
 
Task:
 
<langsyntaxhighlight Jlang="j"> countPopln 3^i.30x
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
30{.(#~ isOdd@countPopln) i. 100 NB. odd population count (aka "ODious numbers")
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
30{.(#~ isEven@countPopln) i. 100 NB. even population count (aka "EVil numbers")
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.math.BigInteger;
 
public class PopCount {
Line 1,269 ⟶ 2,483:
System.out.println();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,282 ⟶ 2,496:
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
// popCountpopulationCount :: Int -> Int
const popCountpopulationCount = n =>
// The number of non-zero bits in the binary
foldl(
// representation of the integer n.
(a, x) => a + (x === '1' ? 1 : 0),
0,sum(unfoldr(
splitOn('',x => 0 < x ? showIntAsBinary(n))
Just(Tuple(x % 2)(Math.floor(x / 2)))
) : Nothing()
)(n));
 
// ----------------------- TEST ------------------------
// main :: IO ()
const main = () => {
const [evens, odds] = Array.from(
partition(compose(even, populationCount))(
enumFromTo(0)(59)
)
);
return [
'Population counts of the first 30 powers of three:',
` [${enumFromTo(0)(29).map(
compose(populationCount, raise(3))
).join(',')}]`,
"\nFirst thirty 'evil' numbers:",
` [${[evens.join(',')]}]`,
"\nFirst thirty 'odious' numbers:",
` [${odds.join(',')}]`
].join('\n');
};
 
// GENERIC FUNCTIONS ------------------------------------------------------
 
// ----------------- GENERIC FUNCTIONS -----------------
// (++) :: [a] -> [a] -> [a]
 
const append = (xs, ys) => xs.concat(ys);
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
 
 
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
 
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
 
 
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
 
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.fromn => !isNaN(m) ? ({
length: MathArray.floorfrom(n - m) + 1{
}, (_, i) => m length: 1 + i);n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
 
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
 
// lengtheven :: [a]Int -> IntBool
const lengtheven = xsn => xs.length;
// True if n is an even number.
0 === n % 2;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// raisepartition :: Num(a -> IntBool) -> Num[a] -> ([a], [a])
const raisepartition = Math.pow;p =>
// A tuple of two lists - those elements in
// xs which match p, and those which don't.
xs => ([...xs]).reduce(
(a, x) =>
p(x) ? (
Tuple(a[0].concat(x))(a[1])
) : Tuple(a[0])(a[1].concat(x)),
Tuple([])([])
);
 
// showIntAsBinary :: Int -> String
const showIntAsBinary = n => n.toString(2);
 
// splitOnraise :: StringNum -> StringInt -> [String]Num
const splitOnraise = (cs, xs)x => xs.split(cs);
// X to the power of n.
n => Math.pow(x, n);
 
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
}
 
// sum :: [Num] -> Num
// TEST -------------------------------------------------------------------
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
 
 
// { popCounts : [Int], evenThenOdd : ([Int], [Int]) }
// unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
return {
const unfoldr = f =>
popCounts: map(x => popCount(raise(3, x)), enumFromTo(0, 30)),
evenThenOdd:v until(=> {
const mxs => length(m.evenOdd[0]) >= 30 && length(m.evenOdd[1]) >= 30,;
let xr = [v, m => ({v];
while (true) x: m.x + 1,{
const mb = evenOdd: popCountf(m.xxr[1]) % 2 === 0 ? (;
if [append(mmb.evenOdd[0], m.xNothing), m.evenOdd[1]]{
)return : [m.evenOdd[0], append(m.evenOdd[1], m.x)]xs
}), else {
x:xr 0,= mb.Just;
evenOdd: xs.push(xr[0])
[],
[]
]
}
)}
.evenOdd};
 
};
// ---
})();</lang>
return main();
})();</syntaxhighlight>
{{Out}}
<pre>Population counts of the first 30 powers of three:
<lang JavaScript>{"popCounts":[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25, 25],
[1,2,2,4,3,6,6,5,6,8,9,13,10,11,14,15,11,14,14,17,17,20,19,22,16,18,24,30,25,25]
"evenThenOdd":[
 
[0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58],
First thirty 'evil' numbers:
[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]]}</lang>
[0,3,5,6,9,10,12,15,17,18,20,23,24,27,29,30,33,34,36,39,40,43,45,46,48,51,53,54,57,58]
 
First thirty 'odious' numbers:
[1,2,4,7,8,11,13,14,16,19,21,22,25,26,28,31,32,35,37,38,41,42,44,47,49,50,52,55,56,59]</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def popcount:
def bin: recurse( if . == 0 then empty else ./2 | floor end ) % 2;
[bin] | add;
Line 1,384 ⟶ 2,663:
;
 
task</langsyntaxhighlight>
{{Out}}
$ jq -n -r -c -f Population_count.jq
Line 1,395 ⟶ 2,674:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">println("First 3 ^ i, up to 29 pop. counts: ", join((count_ones(3 ^ n) for n in 0:29), ", "))
{{works with|Julia|0.6}}
println("Evil numbers: ", join(filter(x -> iseven(count_ones(x)), 0:59), ", "))
 
println("Odious numbers: ", join(filter(x -> isodd(count_ones(x)), 0:59), ", "))</syntaxhighlight>
<lang julia>popcount(n) = sum(digits(n, 2))
 
println("First 3 ^ i, up to 29 pop. counts: ", join((popcount(3 ^ n) for n in 0:29), ", "))
println("Evil numbers: ", join(filter(x -> iseven(popcount(x)), 0:59), ", "))
println("Odious numbers: ", join(filter(x -> isodd(popcount(x)), 0:59), ", "))</lang>
 
{{out}}
Line 1,409 ⟶ 2,684:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun popCount(n: Long) = when {
Line 1,448 ⟶ 2,723:
}
println()
}</langsyntaxhighlight>
 
{{out}}
Line 1,463 ⟶ 2,738:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Take decimal number, return binary string
function dec2bin (n)
local bin, bit = ""
Line 1,505 ⟶ 2,780:
firstThirty("3^x")
firstThirty("Evil")
firstThirty("Odious")</langsyntaxhighlight>
{{out}}
<pre>3^x: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Line 1,511 ⟶ 2,786:
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|MathematicaM2000 Interpreter}}==
 
<lang Mathematica>popcount[n_Integer] := IntegerDigits[n, 2] // Total
=====Using just Count() and loops=====
<syntaxhighlight lang="m2000 interpreter">
Module Population_count{
Function Count(x as long long) {
integer Count
long long m=x
m|div 0x1_0000_0000&&
x|mod 0x1_0000_0000&&
While x<>0&
x=Binary.And(X, X-1&&)
Count++
End While
x=m
While x<>0&
x=Binary.And(X, X-1&&)
Count++
End While
=Count
}
long long i, b=3
stack new {
for i=0 to 29
Data count(b^i)
next
print "3^x population:", array([])#str$()
i=0: b=0
while i<30
if Count(b) mod 2=0 then data b:i++
b++
end while
print "evil numbers:", array([])#str$()
i=0: b=0
while i<30
if Count(b) mod 2=1 then data b:i++
b++
end while
print "odious numbers:", array([])#str$()
}
}
Population_count
</syntaxhighlight>
 
=====Using Generators=====
 
<syntaxhighlight lang="m2000 interpreter">
Module Population_count{
Count=lambda (x as long long)->{
integer Count
long long m=x
m|div 0x1_0000_0000&&
x|mod 0x1_0000_0000&&
While x<>0&
x=Binary.And(X, X-1&&)
Count++
End While
x=m
While x<>0&
x=Binary.And(X, X-1&&)
Count++
End While
=Count
}
series3pow=lambda Count, i=0&& -> {
=count(3&&^i):i++
}
seriesEvil=lambda Count, i=0&&-> {
while Count(i) mod 2=1{i++}
=i:i++
}
seriesOdious=lambda Count, i=0&&-> {
while Count(i) mod 2=0{i++}
=i:i++
}
Dim a(30)<<series3pow()
print "3^x population:", a()#str$()
Dim a(30)<<seriesEvil()
print "evil numbers:", a()#str$()
Dim a(30)<<seriesOdious()
print "odious numbers:", a()#str$()
}
Population_count
</syntaxhighlight>
{{out}}
<pre>
3^x population:1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil numbers:0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious numbers:1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|MAD}}==
 
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION LOWBIT.(K) = K-K/2*2
R FUNCTION TO CALC POP COUNT
INTERNAL FUNCTION(N)
ENTRY TO POPCNT.
RSLT = 0
PCTNUM = N
LOOP PCTNXT = PCTNUM/2
RSLT = RSLT + PCTNUM-PCTNXT*2
PCTNUM = PCTNXT
WHENEVER PCTNUM.NE.0, TRANSFER TO LOOP
FUNCTION RETURN RSLT
END OF FUNCTION
R POP COUNT OF 3^0 TO 3^29
POW3 = 1
THROUGH P3CNT, FOR I=0, 1, I.GE.30
PRINT FORMAT P3FMT, I, POPCNT.(POW3)
P3CNT POW3 = POW3 * 3
VECTOR VALUES P3FMT = $15HPOP COUNT OF 3^,I2,2H: ,I3*$
R EVIL AND ODIOUS NUMBERS
PRINT COMMENT$ $
PRINT COMMENT$ FIRST 30 EVIL NUMBERS ARE$
SEEN = 1
THROUGH EVIL, FOR I=0, 1, SEEN.GE.30
WHENEVER LOWBIT.(POPCNT.(I)).E.0
PRINT FORMAT NUMFMT,I
SEEN = SEEN + 1
EVIL END OF CONDITIONAL
 
PRINT COMMENT$ $
PRINT COMMENT$ FIRST 30 ODIOUS NUMBERS ARE$
SEEN = 1
THROUGH ODIOUS, FOR I=0, 1, SEEN.GE.30
WHENEVER LOWBIT.(POPCNT.(I)).E.1
PRINT FORMAT NUMFMT,I
SEEN = SEEN + 1
ODIOUS END OF CONDITIONAL
VECTOR VALUES NUMFMT = $I2*$
END OF PROGRAM</syntaxhighlight>
 
{{out}}
 
<pre style='height: 40ex'>POP COUNT OF 3^ 0: 1
POP COUNT OF 3^ 1: 2
POP COUNT OF 3^ 2: 2
POP COUNT OF 3^ 3: 4
POP COUNT OF 3^ 4: 3
POP COUNT OF 3^ 5: 6
POP COUNT OF 3^ 6: 6
POP COUNT OF 3^ 7: 5
POP COUNT OF 3^ 8: 6
POP COUNT OF 3^ 9: 8
POP COUNT OF 3^10: 9
POP COUNT OF 3^11: 13
POP COUNT OF 3^12: 10
POP COUNT OF 3^13: 11
POP COUNT OF 3^14: 14
POP COUNT OF 3^15: 15
POP COUNT OF 3^16: 11
POP COUNT OF 3^17: 14
POP COUNT OF 3^18: 14
POP COUNT OF 3^19: 17
POP COUNT OF 3^20: 17
POP COUNT OF 3^21: 20
POP COUNT OF 3^22: 19
POP COUNT OF 3^23: 22
POP COUNT OF 3^24: 16
POP COUNT OF 3^25: 18
POP COUNT OF 3^26: 24
POP COUNT OF 3^27: 30
POP COUNT OF 3^28: 25
POP COUNT OF 3^29: 25
 
FIRST 30 EVIL NUMBERS ARE
0
3
5
6
9
10
12
15
17
18
20
23
24
27
29
30
33
34
36
39
40
43
45
46
48
51
53
54
57
 
FIRST 30 ODIOUS NUMBERS ARE
1
2
4
7
8
11
13
14
16
19
21
22
25
26
28
31
32
35
37
38
41
42
44
47
49
50
52
55
56</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">popcount[n_Integer] := IntegerDigits[n, 2] // Total
Print["population count of powers of 3"]
popcount[#] & /@ (3^Range[0, 30])
Line 1,536 ⟶ 3,045:
]
Print["first thirty odious numbers"]
odiouslist</langsyntaxhighlight>
{{out}}
<pre>population count of powers of 3
Line 1,547 ⟶ 3,056:
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(2 over over mod 'div dip) :divmod2
 
(
Line 1,559 ⟶ 3,068:
"3^n: " print! 30 iota (3 swap pow int pop-count) map puts!
60 iota (pop-count odd?) partition
"Evil: " print! puts! "Odious: " print! puts!</langsyntaxhighlight>
{{out}}
<pre>
Line 1,566 ⟶ 3,075:
Odious: (1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59)
</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map (show . take 30) [powers_of_3, evil, odious]))]
 
powers_of_3 :: [num]
powers_of_3 = map (popcount . (3^)) [0..]
 
evil :: [num]
evil = filter f [0..] where f n = popcount n mod 2 = 0
 
odious :: [num]
odious = filter f [0..] where f n = popcount n mod 2 = 1
 
popcount :: num -> num
popcount 0 = 0
popcount n = n mod 2 + popcount (n div 2)</syntaxhighlight>
{{out}}
<pre>[1,2,2,4,3,6,6,5,6,8,9,13,10,11,14,15,11,14,14,17,17,20,19,22,16,18,24,30,25,25]
[0,3,5,6,9,10,12,15,17,18,20,23,24,27,29,30,33,34,36,39,40,43,45,46,48,51,53,54,57,58]
[1,2,4,7,8,11,13,14,16,19,21,22,25,26,28,31,32,35,37,38,41,42,44,47,49,50,52,55,56,59]</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import bitops
import strformat
 
Line 1,594 ⟶ 3,124:
write(stdout, "\nodious:")
for i in 0..<30:
write(stdout, fmt"{od[i]:2} ")</lang>
write(stdout, '\n')</syntaxhighlight>
 
{{out}}
<pre>
3^x : 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
Another version, in functional style, with most computations done at compile time:
<syntaxhighlight lang="nim">import bitops, math, sequtils, strutils
 
const
N = 30
popcounts = toSeq(0..<N).mapIt(popcount(3^it))
mapping = toSeq(0..<(2 * N)).mapIt((it, it.popcount))
evil = mapping.filterIt((it[1] and 1) == 0).mapIt(it[0])
odious = mapping.filterIt((it[1] and 1) != 0).mapIt(it[0])
 
echo "3^n: ", popcounts.mapIt(($it).align(2)).join(" ")
echo "evil: ", evil.mapIt(($it).align(2)).join(" ")
echo "odious:", odious.mapIt(($it).align(2)).join(" ")</syntaxhighlight>
 
{{out}}
<pre>3^n: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let popcount n =
let rec aux acc = function
| 0 -> acc
| x -> aux (succ acc) (x land pred x)
in
aux 0 n
 
let is_parity p x =
p = 1 land popcount x
 
(* test code *)
 
let powers3_seq () =
Seq.unfold (fun x -> Some (popcount x, x * 3)) 1
 
let parity_seq p =
Seq.(filter (is_parity p) (ints 0))
 
let print_seq_30 s =
Seq.(s |> take 30 |> map string_of_int)
|> List.of_seq |> String.concat " " |> print_endline
 
let () = print_seq_30 (powers3_seq ())
let () = print_seq_30 (parity_seq 0)
let () = print_seq_30 (parity_seq 1)</syntaxhighlight>
{{out}}
<pre>
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|Oforth}}==
<langsyntaxhighlight lang="oforth">: popcount(n)
0 while ( n ) [ n isOdd + n bitRight(1) ->n ] ;
 
Line 1,613 ⟶ 3,198:
 
0 ->count
0 while( count 30 <> ) [ dup popcount isOdd ifTrue: [ dup . count 1+ ->count ] 1+ ] drop ;</langsyntaxhighlight>
 
{{out}}
Line 1,621 ⟶ 3,206:
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59 ok
</pre>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(define (popcount n)
(let loop ((n n) (c 0))
(if (= n 0)
c
(loop (>> n 1)
(if (eq? (band n 1) 0) c (+ c 1))))))
(print (popcount 31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253))
 
 
(define thirty 30)
 
(display "popcount:")
(for-each (lambda (i)
(display " ")
(display (popcount (expt 3 i))))
(iota thirty 0))
(print)
 
(define (evenodd name test)
(display name) (display ":")
(for-each (lambda (i)
(display " ")
(display i))
(reverse
(let loop ((n 0) (i 0) (out '()))
(if (= i thirty)
out
(if (test (popcount n))
(loop (+ n 1) (+ i 1) (cons n out))
(loop (+ n 1) i out))))))
(print))
 
(evenodd "evil" even?)
(evenodd "odius" odd?)
</syntaxhighlight>
{{out}}
<pre>
159
popcount: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odius: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">vector(30,n,hammingweight(3^(n-1)))
od=select(n->hammingweight(n)%2,[0..100]); ev=setminus([0..100],od);
ev[1..30]
od[1..30]</langsyntaxhighlight>
{{out}}
<pre>%1 = [1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
Line 1,636 ⟶ 3,266:
{{works with|freepascal}}
Like Ada a unit is used.
<langsyntaxhighlight lang="pascal">unit popcount;
{$IFDEF FPC}
{$MODE DELPHI}
Line 1,717 ⟶ 3,347:
 
Begin
End.</langsyntaxhighlight>
The program
<langsyntaxhighlight lang="pascal">program pcntTest;
uses
sysutils,popCount;
Line 1,767 ⟶ 3,397:
until k = 30;
writeln(s);
end.</langsyntaxhighlight>
;Output:
<pre>PopCnt 3^i :1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Line 1,775 ⟶ 3,405:
 
Some processors define the <code>card</code> function, which can be used in conjunction with sets:
<langsyntaxhighlight lang="pascal">var
i: integer;
f: set of 0..(bitSizeOf(i)-1) absolute i; // same address as i, but different interpretation
begin
writeLn(card(f));
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
{{trans|Perl 6Raku}}
 
We'll emulate infinite lists with closures.
 
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
 
sub population_count {
my $n = shift;
die "argument can't be negative" if $n < 0;
my $c;
for ($c = 0; $n; $n >>= 1) {
$c += $n & 1;
}
$c;
}
 
print join ' ', map { population_count(3**$_) } 0 .. 30 - 1;
print "\n";
sub evil {
my $i = 0;
sub { $i++ while population_count($i) % 2; $i++ }
}
 
sub odious {
my $i = 0;
Line 1,811 ⟶ 3,431:
}
 
sub population_count {
my ($evil, $odious) = (evil, odious);
my (@evil,$n = @odious)shift;
my $c;
for (1 .. 30) {
for ($c = 0; $n; $n >>= 1) { $c += $n & 1 }
push @evil, $evil->();
$c
push @odious, $odious->();
}
 
say join ' ', map { population_count 3**$_ } 0 .. 30 - 1;
printf "Evil : %s\n", join ' ', @evil;
 
printf "Odious: %s\n", join ' ', @odious;</lang>
my (@evil, @odious);
my ($evil, $odious) = (evil, odious);
push( @evil, $evil->() ), push @odious, $odious->() for 1 .. 30;
 
say "Evil @evil";
say "Odious @odious";</syntaxhighlight>
{{out}}
<pre>1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
 
A faster population count can be done with pack/unpack:
<syntaxhighlight lang="text">say unpack("%b*",pack "J*", 1234567); # J = UV</langsyntaxhighlight>
 
Various modules can also perform a population count, with the first of these being faster than the pack/unpack builtins. The first three easily support bigints, the last will with some adjustment.
<langsyntaxhighlight lang="perl">use ntheory qw/hammingweight/;
say hammingweight(1234567);
 
Line 1,840 ⟶ 3,465:
 
use Bit::Vector;
say Bit::Vector->new_Dec(64,1234567)->Norm;</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<lang perl6>sub population-count(Int $n where * >= 0) { [+] $n.base(2).comb }
 
say map &population-count, 3 «**« ^30;
say "Evil: ", (grep { population-count($_) %% 2 }, 0 .. *)[^30];
say "Odious: ", (grep { population-count($_) % 2 }, 0 .. *)[^30];</lang>
{{out}}
<pre>1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
That's the convenient way to write it, but the following avoids string processing and is therefore about twice as fast:
<lang perl6>sub population-count(Int $n is copy where * >= 0) {
loop (my $c = 0; $n; $n +>= 1) {
$c += $n +& 1;
}
$c;
}</lang>
 
=={{header|Phix}}==
As of 1.0.2 there is a builtin count_bits(), and also mpz_popcount(), both of which match the results from pop_count() below.
<lang Phix>function pop_count(atom n)
<!--<syntaxhighlight lang="phix">(phixonline)-->
if n<0 then ?9/0 end if
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer res = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">pop_count</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
while n!=0 do
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
res += and_bits(n,1)
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
n = floor(n/2)
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
end while
<span style="color: #000000;">res</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
return res
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
 
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
sequence s = {}
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
for i=0 to 29 do
s &= pop_count(power(3,i))
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"3^x pop_counts:%v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">29</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)}),</span><span style="color: #000000;">pop_count</span><span style="color: #0000FF;">)})</span>
end for
puts(1,"3^x pop_counts:") ?s
<span style="color: #008080;">procedure</span> <span style="color: #000000;">eo</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">b0</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">30</span><span style="color: #0000FF;">)</span>
procedure eo(integer b0, string name)
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
integer k=0, l=1
<span style="color: #008080;">while</span> <span style="color: #000000;">l</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">30</span> <span style="color: #008080;">do</span>
while l<=30 do
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pop_count</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">b0</span> <span style="color: #008080;">then</span>
if and_bits(pop_count(k),1)=b0 then
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span>
s[l] = k
<span style="color: #000000;">l</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
l += 1
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
k += 1
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end while
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s numbers:%v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
puts(1,name&" numbers:") ?s
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
end procedure
<span style="color: #000000;">eo</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" evil"</span><span style="color: #0000FF;">)</span>
eo(0," evil")
<span style="color: #000000;">eo</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"odious"</span><span style="color: #0000FF;">)</span>
eo(1,"odious")</lang>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,895 ⟶ 3,503:
evil numbers:{0,3,5,6,9,10,12,15,17,18,20,23,24,27,29,30,33,34,36,39,40,43,45,46,48,51,53,54,57,58}
odious numbers:{1,2,4,7,8,11,13,14,16,19,21,22,25,26,28,31,32,35,37,38,41,42,44,47,49,50,52,55,56,59}
</pre>
 
=={{header|PicoLisp}}==
<lang PicoLisp>(de popz (N)
(cnt
'((N) (= "1" N))
(chop (bin N)) ) )
 
(println
'pops:
(mapcar
'((N) (popz (** 3 N)))
(range 0 29) ) )
(setq N -1)
(println
'evil:
(make
(for (C 0 (> 30 C))
(unless (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) )
(setq N -1)
(println
'odio:
(make
(for (C 0 (> 30 C))
(when (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) )</lang>
{{out}}
<pre>
pops: (1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25)
evil: (0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58)
odio: (1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59)
</pre>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
function convertToBinary($integer) {
$binary = "";
Line 2,001 ⟶ 3,575:
echo "\nfirst 30 odious numbers:";
printFirst30Odious();
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,009 ⟶ 3,583:
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
println(powers_of_three=[pop_count(3**I) : I in 0..29]),
println('evil_numbers '=take_n($evil_number, 30,0)),
println('odious_numbers '=take_n($odious_number, 30,0)),
nl.
 
% Get the first N numbers that satisfies function F, starting with S
take_n(F,N,S) = L =>
I = S,
C = 0,
L = [],
while(C < N)
if call(F,I) then
L := L ++ [I],
C := C + 1
end,
I := I + 1
end.
 
evil_number(N) => pop_count(N) mod 2 == 0.
odious_number(N) => pop_count(N) mod 2 == 1.
 
pop_count(N) = sum([1: I in N.to_binary_string(), I = '1']).</syntaxhighlight>
 
{{out}}
<pre>powers_of_three = [1,2,2,4,3,6,6,5,6,8,9,13,10,11,14,15,11,14,14,17,17,20,19,22,16,18,24,30,25,25]
evil_numbers = [0,3,5,6,9,10,12,15,17,18,20,23,24,27,29,30,33,34,36,39,40,43,45,46,48,51,53,54,57,58]
odious_numbers = [1,2,4,7,8,11,13,14,16,19,21,22,25,26,28,31,32,35,37,38,41,42,44,47,49,50,52,55,56,59]</pre>
 
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(de popz (N)
(cnt
'((N) (= "1" N))
(chop (bin N)) ) )
 
(println
'pops:
(mapcar
'((N) (popz (** 3 N)))
(range 0 29) ) )
(setq N -1)
(println
'evil:
(make
(for (C 0 (> 30 C))
(unless (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) )
(setq N -1)
(println
'odio:
(make
(for (C 0 (> 30 C))
(when (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) )</syntaxhighlight>
{{out}}
<pre>
pops: (1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25)
evil: (0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58)
odio: (1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59)
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function pop-count($n) {
(([Convert]::ToString($n, 2)).toCharArray() | where {$_ -eq '1'}).count
Line 2,019 ⟶ 3,656:
"even pop_count: $($m = $n = 0; while($m -lt 30) {if(0 -eq ((pop-count $n)%2)) {$m += 1; $n}; $n += 1} )"
"odd pop_count: $($m = $n = 0; while($m -lt 30) {if(1 -eq ((pop-count $n)%2)) {$m += 1; $n}; $n += 1} )"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,025 ⟶ 3,662:
even pop_count: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odd pop_count: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">Procedure.i PopCount(n.i) : ProcedureReturn CountString(Bin(Pow(3,n)),"1") : EndProcedure
Procedure PutR(v.i) : Print(RSet(Str(v),3)) : EndProcedure
 
If OpenConsole()
NewList ne() : NewList no()
i=0
While ListSize(ne())+ListSize(no())<60
If CountString(Bin(i),"1")%2=0 : AddElement(ne()) : ne()=i
Else : AddElement(no()) : no()=i : EndIf
i+1
Wend
Print("3^i [i=0..29]") : For i=0 To 29 : PutR(PopCount(i)) : Next : PrintN("")
Print("Evil numbers ") : ForEach ne() : PutR(ne()) : Next : PrintN("")
Print("Odious numb..") : ForEach no() : PutR(no()) : Next : Input()
EndIf</syntaxhighlight>
{{out}}
<pre>
3^i [i=0..29] 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil numbers 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious numb.. 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">>>> def popcount(n): return bin(n).count("1")
...
>>> [popcount(3**i) for i in range(30)]
Line 2,044 ⟶ 3,704:
>>> odious[:30]
[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]
>>> </langsyntaxhighlight>
 
===Python: Kernighans' algorithm===
The algorithm is explained [https://www.techiedelight.com/brian-kernighans-algorithm-count-set-bits-integer/ here]. Replace popcount with pop_kernighan in the example above to get the same evil and odious results.
 
<syntaxhighlight lang="python">def pop_kernighan(n):
i = 0
while n:
i, n = i + 1, n & (n - 1)
return i
</syntaxhighlight>
 
===Composition of pure functions===
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Population count'''
 
from functools import reduce
Line 2,062 ⟶ 3,732:
 
 
# TEST -------------------------- TEST --------------------------
def main():
'''Tests'''
 
print('Population count of first 30 powers of 3:')
print(' ' + showList(
[popCount(pow(3, x)) for x in enumFromTo(0)(29)]
))
 
evilNums, odiousNums = partition(
compose(even)(, popCount)
)(enumFromTo(0)(59))
 
print("\nFirst thirty 'evil' numbers:")
print(' ' + showList(evilNums))
 
print("\nFirst thirty 'odious' numbers:")
print(' ' + showList(odiousNums))
 
 
# GENERIC ------------------------ GENERIC -------------------------
 
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.'''
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
 
Line 2,092 ⟶ 3,764:
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.'''
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
 
 
# compose (<<<) :: (b(a -> ca), ...) -> (a -> ba) -> a -> c
def compose(g*fs):
'''Composition, from right to left,
'''Right to left function composition.'''
of a series of functions.
return lambda f: lambda x: g(f(x))
'''
def go(f, g):
def fg(x):
return f(g(x))
return fg
return reduce(go, fs, lambda x: x)
 
 
# enumFromTo :: (Int, -> Int) -> [Int]
def enumFromTo(m):
'''IntegerEnumeration enumerationof frominteger mvalues to n[m..n]'''
return lambda n: list(range(m, 1 + n))
 
 
# even :: Int -> Bool
def even(x):
'''True if x is aan integer
multiple of two.'''
'''
return 0 == x % 2
 
Line 2,118 ⟶ 3,799:
def partition(p):
'''The pair of lists of those elements in xs
which respectively, do, and don't
satisfy the predicate p.'''
'''
 
def go(a, x):
ts, fs = a
return (ts + [x], fs) if p(x) else (ts, fs + [x])
return lambda xs: reduce(go, xs, ([], []))
 
 
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(repr(x) for x in xs) + ']'
 
 
# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)
# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
def unfoldl(f):
'''Dual to reduce or foldrfoldl.
Where catamorphismthese reducesreduce a list to a summary value, unfoldl
the anamorphic unfoldr builds a list from a seed value.
As long asWhere f returns Just(a, b), a is prependedappended to the list,
and the residual b is used as the argument for the next
application of f.
When f returns Nothing, the completed list is returned.'''
def go(xr):'''
def mb = fgo(xr[0]v):
ifx, mb.get('Nothing'):r = v, v
xs return= []
elsewhile True:
y, rmb = mb.getf('Just'x)
returnif gomb.get((y, r'Nothing')) + [r]:
return xs
 
return lambda x: go((x, x)) else:
x, r = mb.get('Just')
xs.insert(0, r)
return xs
return go
 
 
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Population count of first 30 powers of 3:
[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
 
First thirty 'evil' numbers:
[0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]
 
First thirty 'odious' numbers:
[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 0 swap
[ dup while
dup 1 &
rot + swap
1 >>
again ]
drop ] is popcount ( n --> n )
 
[ 1 & ] is odd ( n --> b )
 
[ odd not ] is even ( n --> b )
 
 
[ ]'[ temp put 0
[ over while
[ dup popcount
temp share do
if [ dup echo sp
dip [ 1 - ] ]
1+ ]
again ]
2drop temp release ] is echopopwith ( n --> )
 
say "Population counts of the first thirty powers of 3." cr
30 times
[ 3 i^ ** popcount echo sp ] cr
cr
say "The first thirty evil numbers." cr
30 echopopwith even cr
cr
say "The first thirty odious numbers." cr
30 echopopwith odd cr</syntaxhighlight>
 
{{out}}
 
<pre>Population counts of the first thirty powers of 3.
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
 
The first thirty evil numbers.
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
 
The first thirty odious numbers.
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|R}}==
By default, R does not support 64-bit integer types. We therefore need the bit64 library and an awkward popCount function in order to make this work. Aside from the ugly one-liner that is the popCount function, the rest is trivial.
<syntaxhighlight lang="rsplus">library(bit64)
popCount <- function(x) sum(as.numeric(strsplit(as.bitstring(as.integer64(x)), "")[[1]]))
finder <- function()
{
odious <- evil <- integer(0)
x <- odiousLength <- evilLength <- 0
while(evilLength + odiousLength != 60)#We could be smarter, but this condition suffices.
{
if(popCount(x) %% 2 == 0) evil[evilLength + 1] <- x else odious[odiousLength + 1] <- x
x <- x + 1
evilLength <- length(evil)
odiousLength <- length(odious)
}
cat("The pop count of the 1st 30 powers of 3 are:", sapply(3^(0:29), popCount), "\n")
cat("The first 30 evil numbers are:", evil, "\n")
cat("The first 30 odious numbers are:", odious)
}
finder()</syntaxhighlight>
{{out}}
<pre>The pop count of the 1st 30 powers of 3 are: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
The first 30 evil numbers are: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
The first 30 odious numbers are: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
;; Positive version from "popcount_4" in:
;; https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
Line 2,203 ⟶ 3,966:
(check-true (odious? 1) "the least odious number")
(check-true (odious? #b1011011011) "seven (which is odd) bits")
(check-false (odious? #b011011011) "six bits... is evil"))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,213 ⟶ 3,976:
(1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub population-count(Int $n where * >= 0) { [+] $n.base(2).comb }
 
say map &population-count, 3 «**« ^30;
say "Evil: ", (grep { population-count($_) %% 2 }, 0 .. *)[^30];
say "Odious: ", (grep { population-count($_) % 2 }, 0 .. *)[^30];</syntaxhighlight>
{{out}}
<pre>1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
That's the convenient way to write it, but the following avoids string processing and is therefore about twice as fast:
<syntaxhighlight lang="raku" line>sub population-count(Int $n is copy where * >= 0) {
loop (my $c = 0; $n; $n +>= 1) {
$c += $n +& 1;
}
$c;
}</syntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Gen 30 All Pow3 (1)>>
<Prout <Gen 30 Evil Iota (0)>>
<Prout <Gen 30 Odious Iota (0)>>;
};
 
Gen {
0 s.Fil s.Gen (s.State) = ;
s.N s.Fil s.Gen (s.State),
<Mu s.Gen s.State>: (s.Next) s.Item,
<Mu s.Fil s.Item>: {
T = s.Item <Gen <- s.N 1> s.Fil s.Gen (s.Next)>;
F = <Gen s.N s.Fil s.Gen (s.Next)>;
};
};
 
Popcount {
0 = 0;
s.N, <Divmod s.N 2>: (s.R) s.B = <+ s.B <Popcount s.R>>;
};
 
Pow3 {
s.N = (<* 3 s.N>) <Popcount s.N>;
};
 
Evil {
s.N, <Mod <Popcount s.N> 2>: {
0 = T;
1 = F;
};
};
 
Odious {
s.N, <Mod <Popcount s.N> 2>: {
0 = F;
1 = T;
};
};
 
All { s.X = T; }
Iota { s.N = (<+ 1 s.N>) s.N; }</syntaxhighlight>
{{out}}
<pre>1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
=={{header|REXX}}==
The &nbsp; ''pop count'' &nbsp; is used in some encryption/decryption methods; &nbsp; a major mainframe manufacturer was coerced &nbsp; <br>(many years ago) &nbsp; to add a hardware instruction to count the bits in a (binary) integer.
<lang rexx>/*REXX program counts the number of "one" bits in the binary version of a decimal number*/
<syntaxhighlight lang="rexx">/*REXX program counts the number of "one" bits in the binary version of a decimal number*/
/*─────────────────── and also generates a specific number of EVIL and ODIOUS numbers.*/
parse arg N B . /*get optional arguments from the C.L. */
if N=='' | N=="," then N=30 30 /*N not specified? Then use default. */
if B=='' | B=="," then B= 3 3 /*B " " " " " */
numeric digits 2000 /*be able to handle gihugeic numbers.*/
numeric digits max(20, length(B**N) ) /*whittle the precision down to size.*/
$= /* [↑] a little calculation for sizing*/
do j=0 for N; $= $ popcountpopCount(B**j) /*generate N popCounts for some powers.*/
end /*j*/ /* [↑] append popCount to the $ list. */
/* [↓] display popcountspopCounts of "3" powers*/
call showList 'popcountspopCounts of the powers of' B /*display the list with a header/title.*/
 
do j=0 until #>=N /*generate N evil numbers. */
if popCount(j) // 2 then iterate /*if odd population count, skip it. */
#= # + 1; $= $ j /*bump evil # count; add it to $ list.*/
end /*j*/ /* [↑] build a list of evil numbers. */
/* [↓] display the evil number list. */
Line 2,237 ⟶ 4,067:
do j=0 until #>=N /*generate N odious numbers. */
if popCount(j) // 2 ==0 then iterate /*if even population count, then skip. */
#= # + 1; $=$ j /*bump odious # count; add to $ list. */
end /*j*/ /* [↑] build a list of odious numbers.*/
/* [↓] display the odious number list.*/
Line 2,245 ⟶ 4,075:
d2b: return word( strip( x2b( d2x( arg(1) ) ), 'L', 0) 0, 1) /*dec ──► bin.*/
popCount: return length( space( translate( d2b(arg(1) ), , 0), 0) ) /*count ones. */
showList: say; say 'The 1st' N arg(1)'":'"; say strip($); #= 0; $=; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
The 1st 30 popcountspopCounts of the powers of 3:
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
 
Line 2,259 ⟶ 4,089:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring"># Project : Population count
<lang ring>
# Project : Population count
 
odds = []
load "stdlib.ring"
nevens = 0[]
nevenpows = 0[]
nodd = 0
binodd = []
bineven = []
binpow = []
while true
n = n + 1
numb = 0
bin = binarydigits(n)
for nr = 1 to len(bin)
if bin[nr] = "1"
numb = numb + 1
ok
next
if numb % 2 = 0
neven = neven + 1
if neven < 31
add(bineven, n)
ok
else
nodd = nodd + 1
if nodd < 31
add(binodd, n)
ok
ok
if neven > 30 and nodd > 30
exit
ok
end
 
for n = 0 to 59
see "3^x:" + nl
if n < 30 add(pows, onesCount(pow(3, n))) ok
for n = 0 to 29
numbnum = 0onesCount(n)
binif num & 1 = binarydigits0 add(powevens, n) else add(3odds, n)) ok
for nr = 1 to len(bin)
if bin[nr] = "1"
numb = numb + 1
ok
next
add(binpow, numb)
next
showarray(binpow)
see nl
 
showOne("3^x:", pows)
see "Evil numbers :" + nl
showOne("Evil numbers:", evens)
showarray(bineven)
showOne("Odious numbers:", odds)
see nl
see "Odious numbers:" + nl
showarray(binodd)
see nl
 
func showarrayonesCount(vectb)
c = see0 "["m = 50
while b svect> = ""0
for n = 1 top len= pow(vect2, m)
if b svect >= svectp +b vect[n]-= +p ",c++ "ok
next m--
end return c
svect = left(svect, len(svect) - 2)
see svect
see "]" + nl
</lang>
Output:
<pre>
3^x:
[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
 
func arrayToStr(ary)
Evil numbers :
res = "[" s = ", "
[3, 4, 5, 6, 9, 10, 12, 15, 16, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57]
for n = 1 to len(ary)
if ary[n] < 10 res += " " ok
if n = len(ary) s = "]" ok
res += "" + ary[n] + s
next return res
 
func showOne(title, ary)
? title
? arrayToStr(ary) + nl</syntaxhighlight>
{{out}}
<pre>3^x:
[ 1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
 
Evil numbers:
[ 0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]
 
Odious numbers:
[ 1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59, 61, 62]</pre>
 
=={{header|RPL}}==
{{Trans|Forth}}
≪ # 0b SWAP
'''WHILE''' DUP # 0b ≠ '''REPEAT'''
DUP # 1b AND ROT + SWAP SR '''END'''
DROP B→R
≫ ''''POPCT'''' STO
≪ '''POPCT''' 2 MOD
≫ ‘'''ODUS?'''’ STO
≪ '''ODUS?''' NOT
≫ ‘'''EVIL?'''’ STO
 
≪ → n
≪ { } # 1b 1 n START
DUP '''POPCT''' ROT SWAP + SWAP 3 * NEXT DROP
{ } # 0b WHILE OVER SIZE n < REPEAT
IF DUP '''EVIL?''' THEN SWAP OVER B→R + SWAP END 1 + END DROP
{ } # 0b WHILE OVER SIZE n < REPEAT
IF DUP '''ODUS?''' THEN SWAP OVER B→R + SWAP END 1 + END DROP
≫ ≫ ‘TASK’ STO
30 TASK
{{out}}
<pre>
3: { 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25 }
2: { 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58 }
1: { 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59 }
</pre>
 
=={{header|Ruby}}==
Demonstrating lazy enumerators.
<langsyntaxhighlight lang="ruby">class Integer
def popcount
Line 2,353 ⟶ 4,181:
puts "Powers of 3:", (0...30).map{|n| (3**n).popcount}.join(' ')
puts "Evil:" , 0.step.lazy.select(&:evil?).first(30).join(' ')
puts "Odious:", 0.step.lazy.reject(&:evil?).first(30).join(' ')</langsyntaxhighlight>
{{Output}}<pre>
Powers of 3:
Line 2,363 ⟶ 4,191:
</pre>
 
=={{Headerheader|Rust}}==
<langsyntaxhighlight Rustlang="rust">fn main() {
let mut num = 1u64;
let mut vec = Vec::new();
Line 2,385 ⟶ 4,213:
println!("\nFirst 30 even pop count:\n{:?}",even);
println!("\nFirst 30 odd pop count:\n{:?}",odd);
}</langsyntaxhighlight>
{{out}}
<pre>pop count of 3^0, 3^1 ... 3^29:
Line 2,395 ⟶ 4,223:
First 30 odd pop count:
[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]</pre>
 
=={{Header|Scala}}==
=={{header|Scala}}==
{{Out}}See it yourself by running in your browser either by [https://scalafiddle.io/sf/1IYuvtd/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/w0oHalRXS1mtI59tXh1NaA Scastie (remote JVM)].
{{libheader|Scala LazyList}}
Line 2,402 ⟶ 4,231:
{{libheader|Scastie qualified}}
{{works with|Scala|2.13}}
<langsyntaxhighlight Scalalang="scala">import java.lang.Long.bitCount
 
object PopCount extends App {
Line 2,420 ⟶ 4,249:
println(series(0L).filter(bitCount(_) % 2 != 0).take(nNumber).mkString(", "))
 
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 2,428 ⟶ 4,257:
is used to compute the population count of the bitset.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func integer: popcount (in integer: n) is
Line 2,459 ⟶ 4,288:
end for;
writeln;
end func;</langsyntaxhighlight>
{{out}}
<pre>1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Line 2,465 ⟶ 4,294:
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59 </pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program population_count;
print([popcount(3**n) : n in [0..29]]);
print([n : n in [0..59] | evil n]);
print([n : n in [0..59] | odious n]);
 
op evil(n);
return even popcount n;
end op;
 
op odious(n);
return odd popcount n;
end op;
 
op popcount(n);
return +/[[n mod 2, n div:=2](1) : until n=0];
end op;
end program;</syntaxhighlight>
{{out}}
<pre>[1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25]
[0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58]
[1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59]</pre>
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func population_count(n) { n.as_bin.count('1') }
say "#{0..29 «**« 3 «call« population_count -> join(' ')}"
 
Line 2,474 ⟶ 4,325:
 
say "Evil: #{numbers.grep{_[1] %% 2}.map{.first}.join(' ')}"
say "Odious: #{numbers.grep{_[1] & 1}.map{.first}.join(' ')}"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,483 ⟶ 4,334:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func populationCount(n: Int) -> Int {
guard n >= 0 else { fatalError() }
 
Line 2,507 ⟶ 4,358:
print("Powers:", Array(pows))
print("Evils:", Array(evils))
print("Odious:", Array(odious))</langsyntaxhighlight>
 
{{out}}
Line 2,513 ⟶ 4,364:
Evils: [0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]
Odious: [1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]</pre>
 
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
 
| Pop Count 3^i
 
i
if i < 30
(3^i) x
popcount x 63 x
~ x $r
+ $r $s
+ ' ' $s
+ i
goif
endif
"' Pop Count 3^i : ' $s " []
 
| Evil Numbers
 
i
cnt
if cnt < 30
popcount i 7 x
x:0:1 y
if y <> 1
+ cnt
~ i $r
+ $r $e
+ ' ' $e
endif
+ i
goif
endif
"' Evil Numbers : ' $e " []
 
| Odious Numbers
 
i
cnt
if cnt < 30
popcount i 7 x
x:0:1 y
if y = 1
+ cnt
~ i $r
+ $r $o
+ ' ' $o
endif
+ i
goif
endif
"' Odious Numbers : ' $o " []
</syntaxhighlight>
 
{{out}}
 
Pop Count 3^i : 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil Numbers : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious Numbers : 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc hammingWeight {n} {
Line 2,529 ⟶ 4,441:
}
puts "evil: [lrange $e 0 29]"
puts "odious: [lrange $o 0 29]"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,539 ⟶ 4,451:
=={{header|UNIX Shell}}==
{{works with|bash}}
<langsyntaxhighlight lang="bash">popcount() {
local -i n=$1
(( n < 0 )) && return 1
Line 2,571 ⟶ 4,483:
done
echo "evil nums: ${evil[*]:0:30}"
echo "odious nums: ${odious[*]:0:30}"</langsyntaxhighlight>
{{output}}
<pre>powers of 3 popcounts: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
evil nums: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
odious nums: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
 
=={{header|VBA}}==
Line 2,582 ⟶ 4,493:
{{works with|VBA|VBA Excel 2013}}
The Decimal subtype of Variant does the job to expand 32-bit integers (Long) to 28-digit integers (Decimal).
<langsyntaxhighlight lang="vb">Sub Population_count()
nmax = 30
b = 3
Line 2,617 ⟶ 4,528:
Wend
popcount = y
End Function 'popcount </langsyntaxhighlight>
{{out}}
<pre>
Line 2,627 ⟶ 4,538:
' 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
 
=={{header|VBScript}}==
Use of the variant currency subtype. Currency mode is a gray area where some operators do not work,
for instance: ^ \ Mod
<langsyntaxhighlight lang="vb">' Population count - VBScript - 10/05/2019
nmax=30
b=3
Line 2,664 ⟶ 4,574:
Wend
popcount=y
End Function 'popcount </langsyntaxhighlight>
{{out}}
<pre>
Line 2,677 ⟶ 4,587:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Console, System.Diagnostics
<lang vbnet>Module Module1
 
Module Module1
Function PopCnt(ByVal n As Long) As Integer
Return Convert.ToString(n, 2).ToCharArray().Where(Function(x) x = "1").Count()
End Function
 
Dim Sub Aline(ByVal ai As List(Of Integer), ByVal titleeo As String)Boolean
 
Console.WriteLine("{0, -8}{1}", title, String.Join(" ", a.Take(30)))
Function PopCnt(n As Long) As Integer
End Sub
Return Convert.ToString(n, 2).ToCharArray().Where(Function(x) x = "1").Count()
End Function
 
Sub Aline(a As List(Of Integer), title As String)
WriteLine("{0,-8}{1}", title, String.Join(" ", a.Take(30)))
End Sub
 
Sub Main(ByVal args As String())
Console.WriteLine("Population Counts:") : Dim t, e, o As New List(Of Integer)
For Dim tc As New List(Of Integer), e= As0 NewTo List(Of Integer), o As New List(Of Integer)99
If (PopCnt(c) ForAnd count As Integer1) = 0 ToThen e.Add(c) Else 99o.Add(c)
If PopCnt(count)c Mod< 2 = 030 Then et.Add(count) Else oPopCnt(CLng(Math.AddPow(count3, c))))
Next
If count < 30 Then t.Add(PopCnt(Math.Pow(3, count)))
Aline(t, "3^n :") : Aline(e, "Evil:") : Aline(o, "Odious:")
Next
' Extra:
Aline(t, "3^n :") : Aline(e, "Evil:") : Aline(o, "Odious:")
WriteLine(vbLf & "Pattern:{0}", Pattern(e, o))
''' Extra:
If Debugger.IsAttached Then ReadKey()
Dim eo As Boolean = e.Contains(0), res As String = "", i As Integer = 0
End Sub
e.Add(0) : o.Add(0)
 
Do
' support routines for pattern output
If eo Then
Function Same(a As List(Of Integer)) As Boolean
If e(i + 1) = e(i) + 1 Then
Return a(i) + 1 res += "͞ " : a(i += 1)
End Function
ElseIf o(i) = e(i) + 1 Then
 
res += "↓" : eo = Not eo
Function Odd(a As List (Of Integer), b As List (Of Integer)) As Boolean
Else
eo = Not eo : If a(i) = resb(i) += "\"1 :Then eoi -= Not eo1 : iReturn += 1True
Return False
End If
End Function
Else
 
If o(i + 1) = o(i) + 1 Then
Function SoO(a As List (Of Integer), b As List (Of Integer), c As String) As String
res += "͢ " : i += 1
Return If(Same(a), c(0), If(Odd(b, a), c(1), c(2)))
ElseIf e(i) = o(i) + 1 Then
End Function
res += "↑" : eo = Not eo
 
Else
Function Either(a As List(Of Integer), b As List(Of Integer)) As String
res += "/" : eo = Not eo : i += 1
Return If(eo, SoO(a, b, "⌢↓↘"), SoO(b, a, "⌣↑↗"))
End If
End IfFunction
 
Loop Until i >= e.Count - 1
Function Pattern(a As List(Of Integer), b As List(Of Integer)) As String
Console.WriteLine(vbLf & "Pattern:{0}", res.Substring(0, res.Count() - 1))
eo = a.Contains(0) : Dim res As New Text.StringBuilder
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
For i = 0 To a.Count - 2 : res.Append(Either(a, b)) : Next
End Sub
Return res.ToString()
End Module
End Function
</lang>
 
End Module</syntaxhighlight>
{{out}}
Added a "Pattern" line. Not quite getting the arrows I wanted, but theThe "Pattern" line shows the sequence pattern of integers for the Evil and Odious output. The pattern goes to about 50, whereas only the first 30 Evil and Odious integers are shown.
<pre>Population Counts:
3^n  : 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
 
Pattern:↓⌣↑↘↑⌢↓⌣↑⌢↓↗↓⌣↑↘↑⌢↓↗↓⌣↑⌢↓⌣↑↘↑⌢↓⌣↑⌢↓↗↓⌣↑⌢↓⌣↑↘↑⌢↓↗↓⌣↑↘↑⌢↓⌣↑⌢↓↗↓⌣↑↘↑⌢↓↗↓⌣↑⌢↓⌣↑↘↑⌢↓↗↓⌣↑↘↑⌢↓⌣↑⌢↓↗↓⌣↑⌢↓⌣</pre>'''P.S.''', The Pattern line may not appear properly on some browsers.
Pattern:↓͢ ↑\↑͞ ↓͢ ↑͞ ↓/↓͢ ↑\↑͞ ↓/↓͢ ↑͞ ↓͢ ↑\↑͞ ↓͢ ↑͞ ↓/↓͢ ↑͞ ↓͢ ↑\↑͞ ↓/↓͢ ↑\↑͞ ↓͢ ↑͞ ↓/↓͢ ↑\↑͞ ↓/↓͢ ↑͞ ↓͢ ↑\↑͞ ↓/↓͢ ↑\↑͞ ↓͢ ↑͞ ↓/↓͢ ↑͞ ↓͢ ↑</pre>'''P.S.''', The underscore-right-arrows and overscore characters on the Pattern line may not appear properly on some browsers.
 
=={{header|Wren}}==
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
The first part is slightly awkward for Wren as 'native' bit-wise operations are limited to unsigned 32-bit integers and 3^21 exceeds this limit. We therefore need to switch to BigInts just before that point to process the remaining powers.
<syntaxhighlight lang="wren">import "./big" for BigInt
import "./fmt" for Fmt
 
var popCount = Fn.new { |n|
var count = 0
while (n != 0) {
n = n & (n - 1)
count = count + 1
}
return count
}
 
System.print("The population count of the first 30 powers of 3 is:")
var p3 = 1
for (i in 0..29) {
System.write("%(popCount.call(p3)) ")
p3 = p3 * 3
if (i == 20) p3 = BigInt.new(p3)
}
var odious = []
System.print("\n\nThe first 30 evil numbers are:")
var count = 0
var n = 0
while (count < 30) {
var pc = popCount.call(n)
if (pc%2 == 0) {
System.write("%(n) ")
count = count + 1
} else {
odious.add(n)
}
n = n + 1
}
odious.add(n)
System.print("\n\nThe first 30 odious numbers are:")
Fmt.print("$d", odious)</syntaxhighlight>
 
{{out}}
<pre>
The population count of the first 30 powers of 3 is:
1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
 
The first 30 evil numbers are:
0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
 
The first 30 odious numbers are:
1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|XPL0}}==
Double precision floating point numbers are used because XPL0's 32-bit
integers don't have sufficient precision to reach 3^29. Double precision
has a 53-bit mantissa that can represent integers up to 2^53, which is
approximately 9.0e15 or approximately 3^33, which is sufficient.
<syntaxhighlight lang "XPL0">func PopCnt(N); \Return count of 1s in binary representation of N
real N; int C;
[C:= 0;
while N >= 0.5 do
[if fix(Mod(N, 2.)) = 1 then C:= C+1;
N:= Floor(N/2.);
];
return C;
];
 
proc Show30(LSb); \Display 30 numbers with even or odd population count
int LSb, C; real N; \Least Significant bit determines even or odd
[N:= 0.; C:= 0;
repeat if (PopCnt(N)&1) = LSb then
[RlOut(0, N); C:= C+1];
N:= N+1.;
until C >= 30;
CrLf(0);
];
 
real N; int P;
[Format(3, 0);
Text(0, "Pow 3: ");
N:= 1.;
for P:= 0 to 29 do
[RlOut(0, float(PopCnt(N))); N:= N*3.];
CrLf(0);
Text(0, "Evil: "); Show30(0);
Text(0, "Odious:"); Show30(1);
]</syntaxhighlight>
{{out}}
<pre>
Pow 3: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59
</pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">print "Pop count (3^x): "
 
for i = 0 to 29
Line 2,766 ⟶ 4,776:
next
return popul
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
Ints have the 1s count as a property.
<langsyntaxhighlight lang="zkl">n:=1; do(30){ print(n.num1s,","); n*=3 } println();
println("evil: ",[0..].filter(30,fcn(n){ n.num1s.isEven }).concat(","));
Line 2,776 ⟶ 4,786:
// now, as an iterator aka lazy:
println("odious: ",(0).walker(*).tweak( // 0,1,2,3,4... iterator
fcn(n){ if(n.num1s.isEven) Void.Skip else n }).walk(30).concat(","));</langsyntaxhighlight>
{{out}}
<pre>
2,114

edits