Population count: Difference between revisions

m
syntax highlighting fixup automation
(Population count in BASIC256)
m (syntax highlighting fixup automation)
Line 39:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F popcount(n)
R bin(n).count(‘1’)
 
Line 55:
 
print(evil[0.<30])
print(odious[0.<30])</langsyntaxhighlight>
 
{{out}}
Line 70:
* 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 151:
CC DS C
REGEQU
END POPCNT </langsyntaxhighlight>
{{out}}
<pre>
Line 165:
It will only run correctly on a real 8080.
 
<langsyntaxhighlight lang="8080asm"> org 100h
mvi e,30 ; 3^0 to 3^29 inclusive
powers: push d ; Keep counter
Line 262:
nl: db 13,10,'$'
pow3: db 1,0,0,0,0,0 ; pow3, starts at 1
pow3c: equ $ ; room for copy</langsyntaxhighlight>
 
{{out}}
Line 272:
=={{header|8086 Assembly}}==
 
<langsyntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
Line 361:
mov dl,' '
int 21h
ret</langsyntaxhighlight>
 
{{out}}
Line 373:
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 397:
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 437:
end loop;
New_Line;
end Test_Pop_Count;</langsyntaxhighlight>
 
{{out}}
Line 446:
 
=={{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 487:
OD;
print( ( newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 496:
 
=={{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 564:
end odious_numbers_loop
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 573:
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
<lang APL>
APL (DYALOG APL)
popDemo←{⎕IO←0
Line 601:
'***Passes' '***Fails'⊃⍨(ans3≢act3)∨(actEvil≢ansEvil)∨(actOdious≢ansOdious)
}
</syntaxhighlight>
</lang>
{{out}}
popDemo 30
Line 613:
 
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">--------------------- POPULATION COUNT ---------------------
 
-- populationCount :: Int -> Int
Line 835:
set my text item delimiters to dlm
s
end unlines</langsyntaxhighlight>
{{Out}}
<pre>Population counts of the first 30 powers of three:
Line 849:
===Straightforward===
 
<langsyntaxhighlight lang="applescript">on popCount(n)
set counter to 0
repeat until (n is 0)
Line 881:
as text
set AppleScript's text item delimiters to astid
return output</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight 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"</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">popCount: function [num][
size select split to :string as.binary num 'x -> x="1"
]
Line 903:
 
print "first thirty odious numbers"
print take select 0..100 => [odd? popCount &] 30</langsyntaxhighlight>
 
{{out}}
Line 915:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, 30
Out1 .= PopCount(3 ** (A_Index - 1)) " "
Loop, 60
Line 927:
, 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
Line 934:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f POPULATION_COUNT.AWK
# converted from VBSCRIPT
Line 971:
return(y)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 981:
=={{header|BASIC256}}==
{{trans|Yabasic}}
<langsyntaxhighlight BASIC256lang="basic256">print "Pop cont (3^x): ";
for i = 0 to 29
print population(3^i); " "; #los últimos números no los muestra correctamente
Line 1,015:
next i
return popul
end function</langsyntaxhighlight>
{{out}}
<pre>Same as Yabasic entry.</pre>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
// Definitions
Line 1,089:
printFirst(30, evil)
printFirst(30, odious)
$)</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 1,095:
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}}==
<langsyntaxhighlight lang="bqn">PopCount ← {(2|𝕩)+𝕊⍟×⌊𝕩÷2}
Odious ← 2|PopCount
Evil ← ¬Odious
Line 1,102:
>⟨PopCount¨ 3⋆↕30,
Evil _List 30,
Odious _List 30⟩</langsyntaxhighlight>
{{out}}
<pre>┌─
Line 1,112:
=={{header|C}}==
{{works with|GCC}}
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main() {
Line 1,150:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,160:
 
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 1,175:
b = (b + (b >> 4)) & 0x0f0f0f0f;
return (b * 0x01010101) >> 24;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Linq;
Line 1,249:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,260:
=={{header|C++}}==
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <bitset>
#include <climits>
Line 1,301:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,311:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn population-count [n]
(Long/bitCount n)) ; use Java inter-op
Line 1,339:
 
(defn odious-numbers []
(filter odious? (integers)))</langsyntaxhighlight>
 
{{out}}
Line 1,361:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">pop_count = proc (n: int) returns (int)
p: int := 0
while n>0 do
Line 1,406:
end
stream$putl(po, "")
end start_up</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 1,413:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. HAMMING.
 
Line 1,485:
DIVIDE 2 INTO POPCOUNT-IN.
IF BIT-IS-SET, ADD 1 TO POPCOUNT-OUT.
MOVE POPCOUNT-REST TO POPCOUNT-IN.</langsyntaxhighlight>
{{out}}
<pre> 3^ EVIL ODD
Line 1,520:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(format T "3^x: ~{~a ~}~%"
(loop for i below 30
collect (logcount (expt 3 i))))
Line 1,531:
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
Line 1,540:
{{trans|Ruby}}
For Crystal select|reject are inherently lazy enumerators, and has popcount for upto unsigned 64-bit integers.
<langsyntaxhighlight lang="ruby">struct Int
def evil?
self >= 0 && popcount.even?
Line 1,548:
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(' ')</langsyntaxhighlight>
{{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
Line 1,558:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, core.bitop;
 
Line 1,566:
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]
Line 1,575:
{{libheader| System.SysUtils, Math}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Population_count;
 
Line 1,641:
end.
 
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Population do
 
def count(n), do: count(<<n :: integer>>, 0)
Line 1,663:
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 1,676:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(population_count).
-export([popcount/1]).
 
Line 1,725:
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 1,734:
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#}}==
<langsyntaxhighlight 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
Line 1,743:
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>
</lang>
{{out}}
<pre>
Line 1,751:
</pre>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel lists lists.lazy math math.bitwise
math.functions namespaces prettyprint.config sequences ;
 
Line 1,760:
100 margin set 0 lfrom [ 3^n ] [ evil ] [ odious ] tri
[ 30 swap ltake list>array ] tri@
"3^n: %u\nEvil: %u\nOdious: %u\n" printf</langsyntaxhighlight>
{{out}}
<pre>
Line 1,769:
 
=={{header|Fermat}}==
<langsyntaxhighlight 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.
 
Line 1,778:
e:=0
n:=0
while e<30 do if Odiousness(n)=1 then !n;!' ';e:=e+1 fi; n:=n+1 od</langsyntaxhighlight>
 
=={{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 1,801:
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 1,809:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program population_count
implicit none
 
Line 1,859:
 
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 1,869:
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 1,930:
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
Line 1,945:
 
=={{Header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
#define NTERMS 30
 
Line 1,982:
print s_tp
print s_evil
print s_odious</langsyntaxhighlight>
{{out}}
<pre>
Line 1,992:
=={{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 2,019:
Print "1st 30 Odious numbers =\t" & sOdious 'Print Odious
 
End</langsyntaxhighlight>
Output:
<pre>
Line 2,030:
===Standard Library===
As of Go 1.9, this function is in the standard Library.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,067:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,079:
===Implementation===
Method of WP example '''popcount_3''':
<langsyntaxhighlight lang="go">func pop64(w uint64) int {
const (
ff = 1<<64 - 1
Line 2,091:
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 2,099:
}
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 2,112:
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 2,122:
Or, if we want to write our own popCount, perhaps something like:
 
<langsyntaxhighlight lang="haskell">import Data.Bifoldable (biList)
import Data.List (partition, unfoldr)
import Data.Tuple (swap)
Line 2,143:
( (popCount . (3 ^) <$> [0 .. 29]) :
biList (partition (even . popCount) [0 .. 59])
)</langsyntaxhighlight>
{{Out}}
<pre>Population count of powers of 3:
Line 2,156:
=={{header|Idris}}==
 
<langsyntaxhighlight Idrislang="idris">module Main
import Data.Vect
 
Line 2,195:
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 2,205:
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 2,275:
System.out.println();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,288:
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,417:
// ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Population counts of the first 30 powers of three:
Line 2,430:
=={{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 2,455:
;
 
task</langsyntaxhighlight>
{{Out}}
$ jq -n -r -c -f Population_count.jq
Line 2,466:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">println("First 3 ^ i, up to 29 pop. counts: ", join((count_ones(3 ^ n) for n in 0:29), ", "))
println("Evil numbers: ", join(filter(x -> iseven(count_ones(x)), 0:59), ", "))
println("Odious numbers: ", join(filter(x -> isodd(count_ones(x)), 0:59), ", "))</langsyntaxhighlight>
 
{{out}}
Line 2,476:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun popCount(n: Long) = when {
Line 2,515:
}
println()
}</langsyntaxhighlight>
 
{{out}}
Line 2,530:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Take decimal number, return binary string
function dec2bin (n)
local bin, bit = ""
Line 2,572:
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 2,580:
=={{header|MAD}}==
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION LOWBIT.(K) = K-K/2*2
Line 2,623:
VECTOR VALUES NUMFMT = $I2*$
END OF PROGRAM</langsyntaxhighlight>
 
{{out}}
Line 2,722:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">popcount[n_Integer] := IntegerDigits[n, 2] // Total
Print["population count of powers of 3"]
popcount[#] & /@ (3^Range[0, 30])
Line 2,746:
]
Print["first thirty odious numbers"]
odiouslist</langsyntaxhighlight>
{{out}}
<pre>population count of powers of 3
Line 2,757:
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(2 over over mod 'div dip) :divmod2
 
(
Line 2,769:
"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 2,778:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import bitops
import strformat
 
Line 2,805:
for i in 0..<30:
write(stdout, fmt"{od[i]:2} ")
write(stdout, '\n')</langsyntaxhighlight>
 
{{out}}
Line 2,815:
 
Another version, in functional style, with most computations done at compile time:
<langsyntaxhighlight Nimlang="nim">import bitops, math, sequtils, strutils
 
const
Line 2,826:
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(" ")</langsyntaxhighlight>
 
{{out}}
Line 2,834:
 
=={{header|Oforth}}==
<langsyntaxhighlight lang="oforth">: popcount(n)
0 while ( n ) [ n isOdd + n bitRight(1) ->n ] ;
 
Line 2,845:
 
0 ->count
0 while( count 30 <> ) [ dup popcount isOdd ifTrue: [ dup . count 1+ ->count ] 1+ ] drop ;</langsyntaxhighlight>
 
{{out}}
Line 2,856:
 
=={{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 2,868:
{{works with|freepascal}}
Like Ada a unit is used.
<langsyntaxhighlight lang="pascal">unit popcount;
{$IFDEF FPC}
{$MODE DELPHI}
Line 2,949:
 
Begin
End.</langsyntaxhighlight>
The program
<langsyntaxhighlight lang="pascal">program pcntTest;
uses
sysutils,popCount;
Line 2,999:
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 3,007:
 
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}}==
Line 3,019:
We'll emulate infinite lists with closures.
 
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 3,047:
 
say "Evil @evil";
say "Odious @odious";</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 3,054:
 
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 3,067:
 
use Bit::Vector;
say Bit::Vector->new_Dec(64,1234567)->Norm;</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 3,098:
<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>
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,107:
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
function convertToBinary($integer) {
$binary = "";
Line 3,176:
echo "\nfirst 30 odious numbers:";
printFirst30Odious();
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,185:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
println(powers_of_three=[pop_count(3**I) : I in 0..29]),
println('evil_numbers '=take_n($evil_number, 30,0)),
Line 3,207:
odious_number(N) => pop_count(N) mod 2 == 1.
 
pop_count(N) = sum([1: I in N.to_binary_string(), I = '1']).</langsyntaxhighlight>
 
{{out}}
Line 3,216:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de popz (N)
(cnt
'((N) (= "1" N))
Line 3,241:
(when (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 3,250:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function pop-count($n) {
(([Convert]::ToString($n, 2)).toCharArray() | where {$_ -eq '1'}).count
Line 3,257:
"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 3,266:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.i PopCount(n.i) : ProcedureReturn CountString(Bin(Pow(3,n)),"1") : EndProcedure
Procedure PutR(v.i) : Print(RSet(Str(v),3)) : EndProcedure
 
Line 3,280:
Print("Evil numbers ") : ForEach ne() : PutR(ne()) : Next : PrintN("")
Print("Odious numb..") : ForEach no() : PutR(no()) : Next : Input()
EndIf</langsyntaxhighlight>
{{out}}
<pre>
Line 3,290:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">>>> def popcount(n): return bin(n).count("1")
...
>>> [popcount(3**i) for i in range(30)]
Line 3,305:
>>> 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.
 
<langsyntaxhighlight lang="python">def pop_kernighan(n):
i = 0
while n:
i, n = i + 1, n & (n - 1)
return i
</syntaxhighlight>
</lang>
 
===Composition of pure functions===
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Population count'''
 
from functools import reduce
Line 3,444:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Population count of first 30 powers of 3:
Line 3,457:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 swap
[ dup while
dup 1 &
Line 3,488:
cr
say "The first thirty odious numbers." cr
30 echopopwith odd cr</langsyntaxhighlight>
 
{{out}}
Line 3,503:
=={{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.
<langsyntaxhighlight lang="rsplus">library(bit64)
popCount <- function(x) sum(as.numeric(strsplit(as.bitstring(as.integer64(x)), "")[[1]]))
finder <- function()
Line 3,520:
cat("The first 30 odious numbers are:", odious)
}
finder()</langsyntaxhighlight>
{{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
Line 3,527:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
;; Positive version from "popcount_4" in:
;; https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
Line 3,567:
(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 3,580:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>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];</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 3,590:
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" perl6line>sub population-count(Int $n is copy where * >= 0) {
loop (my $c = 0; $n; $n +>= 1) {
$c += $n +& 1;
}
$c;
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight 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. */
Line 3,629:
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>
Line 3,643:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring"># Project : Population count
 
odds = []
Line 3,677:
func showOne(title, ary)
? title
? arrayToStr(ary) + nl</langsyntaxhighlight>
{{out}}
<pre>3^x:
Line 3,690:
=={{header|Ruby}}==
Demonstrating lazy enumerators.
<langsyntaxhighlight lang="ruby">class Integer
def popcount
Line 3,704:
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 3,715:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">fn main() {
let mut num = 1u64;
let mut vec = Vec::new();
Line 3,736:
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 3,754:
{{libheader|Scastie qualified}}
{{works with|Scala|2.13}}
<langsyntaxhighlight Scalalang="scala">import java.lang.Long.bitCount
 
object PopCount extends App {
Line 3,772:
println(series(0L).filter(bitCount(_) % 2 != 0).take(nNumber).mkString(", "))
 
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 3,780:
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 3,811:
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 3,818:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func population_count(n) { n.as_bin.count('1') }
say "#{0..29 «**« 3 «call« population_count -> join(' ')}"
 
Line 3,826:
 
say "Evil: #{numbers.grep{_[1] %% 2}.map{.first}.join(' ')}"
say "Odious: #{numbers.grep{_[1] & 1}.map{.first}.join(' ')}"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,835:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func populationCount(n: Int) -> Int {
guard n >= 0 else { fatalError() }
 
Line 3,859:
print("Powers:", Array(pows))
print("Evils:", Array(evils))
print("Odious:", Array(odious))</langsyntaxhighlight>
 
{{out}}
Line 3,868:
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>
 
| Pop Count 3^i
Line 3,919:
endif
"' Odious Numbers : ' $o " []
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,929:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc hammingWeight {n} {
Line 3,942:
}
puts "evil: [lrange $e 0 29]"
puts "odious: [lrange $o 0 29]"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,952:
=={{header|UNIX Shell}}==
{{works with|bash}}
<langsyntaxhighlight lang="bash">popcount() {
local -i n=$1
(( n < 0 )) && return 1
Line 3,984:
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
Line 3,994:
{{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 4,029:
Wend
popcount = y
End Function 'popcount </langsyntaxhighlight>
{{out}}
<pre>
Line 4,043:
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 4,075:
Wend
popcount=y
End Function 'popcount </langsyntaxhighlight>
{{out}}
<pre>
Line 4,088:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Console, System.Diagnostics
 
Module Module1
Line 4,138:
End Function
 
End Module</langsyntaxhighlight>
{{out}}
Added a "Pattern" line. The "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.
Line 4,152:
{{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.
<langsyntaxhighlight lang="ecmascript">import "/big" for BigInt
import "/fmt" for Fmt
 
Line 4,187:
odious.add(n)
System.print("\n\nThe first 30 odious numbers are:")
Fmt.print("$d", odious)</langsyntaxhighlight>
 
{{out}}
Line 4,202:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">print "Pop count (3^x): "
 
for i = 0 to 29
Line 4,235:
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 4,245:
// 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>
10,327

edits