Population count: Difference between revisions
m
syntax highlighting fixup automation
(Population count in BASIC256) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 39:
{{trans|Python}}
<
R bin(n).count(‘1’)
Line 55:
print(evil[0.<30])
print(odious[0.<30])</
{{out}}
Line 70:
* in Unnormalized Double Floating Point, one is implemented X'4E00000000000001'
<br>
<
POPCNT CSECT
USING POPCNT,R13 base register
Line 151:
CC DS C
REGEQU
END POPCNT </
{{out}}
<pre>
Line 165:
It will only run correctly on a real 8080.
<
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</
{{out}}
Line 272:
=={{header|8086 Assembly}}==
<
bits 16
org 100h
Line 361:
mov dl,' '
int 21h
ret</
{{out}}
Line 373:
Specification and implementation of an auxiliary package "Population_Count". The same package is used for [[Pernicious numbers#Ada]]
<
package Population_Count is
subtype Num is Interfaces.Unsigned_64;
function Pop_Count(N: Num) return Natural;
end Population_Count;</
<
function Pop_Count(N: Num) return Natural is
Line 397:
end Pop_Count;
end Population_Count;</
The main program:
<
procedure Test_Pop_Count is
Line 437:
end loop;
New_Line;
end Test_Pop_Count;</
{{out}}
Line 446:
=={{header|ALGOL 68}}==
<
# integer n #
PROC population count = ( LONG INT n )INT:
Line 487:
OD;
print( ( newline ) )
</syntaxhighlight>
{{out}}
<pre>
Line 496:
=={{header|ALGOL W}}==
<
% 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.</
{{out}}
<pre>
Line 573:
=={{header|APL}}==
<syntaxhighlight lang="apl">
APL (DYALOG APL)
popDemo←{⎕IO←0
Line 601:
'***Passes' '***Fails'⊃⍨(ans3≢act3)∨(actEvil≢ansEvil)∨(actOdious≢ansOdious)
}
</syntaxhighlight>
{{out}}
popDemo 30
Line 613:
{{Trans|JavaScript}}
<
-- populationCount :: Int -> Int
Line 835:
set my text item delimiters to dlm
s
end unlines</
{{Out}}
<pre>Population counts of the first 30 powers of three:
Line 849:
===Straightforward===
<
set counter to 0
repeat until (n is 0)
Line 881:
as text
set AppleScript's text item delimiters to astid
return output</
{{output}}
<
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"</
=={{header|Arturo}}==
<
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</
{{out}}
Line 915:
=={{header|AutoHotkey}}==
<
Out1 .= PopCount(3 ** (A_Index - 1)) " "
Loop, 60
Line 927:
, x := (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
return (x * 0x0101010101010101) >> 56
}</
{{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">
# syntax: GAWK -f POPULATION_COUNT.AWK
# converted from VBSCRIPT
Line 971:
return(y)
}
</syntaxhighlight>
{{out}}
<pre>
Line 981:
=={{header|BASIC256}}==
{{trans|Yabasic}}
<
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</
{{out}}
<pre>Same as Yabasic entry.</pre>
=={{header|BCPL}}==
<
// Definitions
Line 1,089:
printFirst(30, evil)
printFirst(30, odious)
$)</
{{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}}==
<
Odious ← 2|PopCount
Evil ← ¬Odious
Line 1,102:
>⟨PopCount¨ 3⋆↕30,
Evil _List 30,
Odious _List 30⟩</
{{out}}
<pre>┌─
Line 1,112:
=={{header|C}}==
{{works with|GCC}}
<
int main() {
Line 1,150:
return 0;
}</
{{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:
<
#define HAVE_BUILTIN_POPCOUNTLL
#endif
Line 1,175:
b = (b + (b >> 4)) & 0x0f0f0f0f;
return (b * 0x01010101) >> 24;
}</
=={{header|C sharp|C#}}==
<
using System;
using System.Linq;
Line 1,249:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,260:
=={{header|C++}}==
{{works with|C++11}}
<
#include <bitset>
#include <climits>
Line 1,301:
return 0;
}</
{{out}}
<pre>
Line 1,311:
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn population-count [n]
(Long/bitCount n)) ; use Java inter-op
Line 1,339:
(defn odious-numbers []
(filter odious? (integers)))</
{{out}}
Line 1,361:
=={{header|CLU}}==
<
p: int := 0
while n>0 do
Line 1,406:
end
stream$putl(po, "")
end start_up</
{{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}}==
<
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.</
{{out}}
<pre> 3^ EVIL ODD
Line 1,520:
=={{header|Common Lisp}}==
<
(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))</
{{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.
<
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(' ')</
{{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}}==
<
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));
}</
{{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">
program Population_count;
Line 1,641:
end.
</syntaxhighlight>
=={{header|Elixir}}==
<
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)</
{{out}}
Line 1,676:
=={{header|Erlang}}==
<
-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)]).</
{{out}}
<
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</
=={{header|F_Sharp|F#}}==
<
// 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>
{{out}}
<pre>
Line 1,751:
</pre>
=={{header|Factor}}==
<
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</
{{out}}
<pre>
Line 1,769:
=={{header|Fermat}}==
<
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</
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<
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</
{{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}}
<
implicit none
Line 1,859:
end function
end program</
{{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.
<
var
// general advice: iterator variables are _signed_
Line 1,930:
end;
writeLn();
end.</
{{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}}==
<
#define NTERMS 30
Line 1,982:
print s_tp
print s_evil
print s_odious</
{{out}}
<pre>
Line 1,992:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=538335b7b71f5ea7b59c0c82fbb0ea3e Click this link to run this code]'''
<
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</
Output:
<pre>
Line 2,030:
===Standard Library===
As of Go 1.9, this function is in the standard Library.
<
import (
Line 2,067:
}
fmt.Println()
}</
{{out}}
<pre>
Line 2,079:
===Implementation===
Method of WP example '''popcount_3''':
<
const (
ff = 1<<64 - 1
Line 2,091:
w = (w + w>>4) & maskf
return int(w * maskp >> 56)
}</
Method of WP example '''popcount_4''':
<
for w != 0 {
w &= w - 1
Line 2,099:
}
return
}</
=={{header|Haskell}}==
{{works with|GHC|7.4+}}
<
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])</
{{out}}
<pre>
Line 2,122:
Or, if we want to write our own popCount, perhaps something like:
<
import Data.List (partition, unfoldr)
import Data.Tuple (swap)
Line 2,143:
( (popCount . (3 ^) <$> [0 .. 29]) :
biList (partition (even . popCount) [0 .. 59])
)</
{{Out}}
<pre>Population count of powers of 3:
Line 2,156:
=={{header|Idris}}==
<
import Data.Vect
Line 2,195:
printCompact (filterUnfoldN 30 isEvil id (1 +) 0)
putStr "Odious: "
printCompact (filterUnfoldN 30 isOdious id (1 +) 0)</
{{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:
<
isOdd=: 1 = 2&|
isEven=: 0 = 2&|</
Task:
<
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</
=={{header|Java}}==
<
public class PopCount {
Line 2,275:
System.out.println();
}
}</
{{out}}
<pre>
Line 2,288:
===ES6===
<
'use strict';
Line 2,417:
// ---
return main();
})();</
{{Out}}
<pre>Population counts of the first 30 powers of three:
Line 2,430:
=={{header|jq}}==
{{works with|jq|1.4}}
<
def bin: recurse( if . == 0 then empty else ./2 | floor end ) % 2;
[bin] | add;
Line 2,455:
;
task</
{{Out}}
$ jq -n -r -c -f Population_count.jq
Line 2,466:
=={{header|Julia}}==
<
println("Evil numbers: ", join(filter(x -> iseven(count_ones(x)), 0:59), ", "))
println("Odious numbers: ", join(filter(x -> isodd(count_ones(x)), 0:59), ", "))</
{{out}}
Line 2,476:
=={{header|Kotlin}}==
<
fun popCount(n: Long) = when {
Line 2,515:
}
println()
}</
{{out}}
Line 2,530:
=={{header|Lua}}==
<
function dec2bin (n)
local bin, bit = ""
Line 2,572:
firstThirty("3^x")
firstThirty("Evil")
firstThirty("Odious")</
{{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}}==
<
INTERNAL FUNCTION LOWBIT.(K) = K-K/2*2
Line 2,623:
VECTOR VALUES NUMFMT = $I2*$
END OF PROGRAM</
{{out}}
Line 2,722:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Print["population count of powers of 3"]
popcount[#] & /@ (3^Range[0, 30])
Line 2,746:
]
Print["first thirty odious numbers"]
odiouslist</
{{out}}
<pre>population count of powers of 3
Line 2,757:
=={{header|min}}==
{{works with|min|0.19.3}}
<
(
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!</
{{out}}
<pre>
Line 2,778:
=={{header|Nim}}==
<
import strformat
Line 2,805:
for i in 0..<30:
write(stdout, fmt"{od[i]:2} ")
write(stdout, '\n')</
{{out}}
Line 2,815:
Another version, in functional style, with most computations done at compile time:
<
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(" ")</
{{out}}
Line 2,834:
=={{header|Oforth}}==
<
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 ;</
{{out}}
Line 2,856:
=={{header|PARI/GP}}==
<
od=select(n->hammingweight(n)%2,[0..100]); ev=setminus([0..100],od);
ev[1..30]
od[1..30]</
{{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.
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 2,949:
Begin
End.</
The program
<
uses
sysutils,popCount;
Line 2,999:
until k = 30;
writeln(s);
end.</
;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:
<
i: integer;
f: set of 0..(bitSizeOf(i)-1) absolute i; // same address as i, but different interpretation
begin
writeLn(card(f));
end;</
=={{header|Perl}}==
Line 3,019:
We'll emulate infinite lists with closures.
<
use warnings;
use feature 'say';
Line 3,047:
say "Evil @evil";
say "Odious @odious";</
{{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</
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.
<
say hammingweight(1234567);
Line 3,067:
use Bit::Vector;
say Bit::Vector->new_Dec(64,1234567)->Norm;</
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 3,107:
=={{header|PHP}}==
<syntaxhighlight lang="php">
function convertToBinary($integer) {
$binary = "";
Line 3,176:
echo "\nfirst 30 odious numbers:";
printFirst30Odious();
</syntaxhighlight>
{{out}}
<pre>
Line 3,185:
=={{header|Picat}}==
<
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']).</
{{out}}
Line 3,216:
=={{header|PicoLisp}}==
<
(cnt
'((N) (= "1" N))
Line 3,241:
(when (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) )</
{{out}}
<pre>
Line 3,250:
=={{header|PowerShell}}==
<syntaxhighlight 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>
<b>Output:</b>
<pre>
Line 3,266:
=={{header|PureBasic}}==
<
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</
{{out}}
<pre>
Line 3,290:
=={{header|Python}}==
===Procedural===
<
...
>>> [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]
>>> </
===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.
<
i = 0
while n:
i, n = i + 1, n & (n - 1)
return i
</syntaxhighlight>
===Composition of pure functions===
{{Works with|Python|3}}
<
from functools import reduce
Line 3,444:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Population count of first 30 powers of 3:
Line 3,457:
=={{header|Quackery}}==
<
[ dup while
dup 1 &
Line 3,488:
cr
say "The first thirty odious numbers." cr
30 echopopwith odd cr</
{{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.
<
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()</
{{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}}==
<
;; 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"))</
{{out}}
<pre>
Line 3,580:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say map &population-count, 3 «**« ^30;
say "Evil: ", (grep { population-count($_) %% 2 }, 0 .. *)[^30];
say "Odious: ", (grep { population-count($_) % 2 }, 0 .. *)[^30];</
{{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"
loop (my $c = 0; $n; $n +>= 1) {
$c += $n +& 1;
}
$c;
}</
=={{header|REXX}}==
The ''pop count'' is used in some encryption/decryption methods; a major mainframe manufacturer was coerced <br>(many years ago) to add a hardware instruction to count the bits in a (binary) integer.
<
/*─────────────────── 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</
{{out|output|text= when using the default input:}}
<pre>
Line 3,643:
=={{header|Ring}}==
<
odds = []
Line 3,677:
func showOne(title, ary)
? title
? arrayToStr(ary) + nl</
{{out}}
<pre>3^x:
Line 3,690:
=={{header|Ruby}}==
Demonstrating lazy enumerators.
<
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(' ')</
{{Output}}<pre>
Powers of 3:
Line 3,715:
=={{header|Rust}}==
<
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);
}</
{{out}}
<pre>pop count of 3^0, 3^1 ... 3^29:
Line 3,754:
{{libheader|Scastie qualified}}
{{works with|Scala|2.13}}
<
object PopCount extends App {
Line 3,772:
println(series(0L).filter(bitCount(_) % 2 != 0).take(nNumber).mkString(", "))
}</
=={{header|Seed7}}==
Line 3,780:
is used to compute the population count of the bitset.
<
const func integer: popcount (in integer: n) is
Line 3,811:
end for;
writeln;
end func;</
{{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}}==
<
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(' ')}"</
{{out}}
<pre>
Line 3,835:
=={{header|Swift}}==
<
guard n >= 0 else { fatalError() }
Line 3,859:
print("Powers:", Array(pows))
print("Evils:", Array(evils))
print("Odious:", Array(odious))</
{{out}}
Line 3,868:
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
| Pop Count 3^i
Line 3,919:
endif
"' Odious Numbers : ' $o " []
</syntaxhighlight>
{{out}}
Line 3,929:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<
proc hammingWeight {n} {
Line 3,942:
}
puts "evil: [lrange $e 0 29]"
puts "odious: [lrange $o 0 29]"</
{{out}}
<pre>
Line 3,952:
=={{header|UNIX Shell}}==
{{works with|bash}}
<
local -i n=$1
(( n < 0 )) && return 1
Line 3,984:
done
echo "evil nums: ${evil[*]:0:30}"
echo "odious nums: ${odious[*]:0:30}"</
{{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).
<
nmax = 30
b = 3
Line 4,029:
Wend
popcount = y
End Function 'popcount </
{{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
<
nmax=30
b=3
Line 4,075:
Wend
popcount=y
End Function 'popcount </
{{out}}
<pre>
Line 4,088:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 4,138:
End Function
End Module</
{{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.
<
import "/fmt" for Fmt
Line 4,187:
odious.add(n)
System.print("\n\nThe first 30 odious numbers are:")
Fmt.print("$d", odious)</
{{out}}
Line 4,202:
=={{header|Yabasic}}==
<
for i = 0 to 29
Line 4,235:
next
return popul
end sub</
=={{header|zkl}}==
Ints have the 1s count as a property.
<
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(","));</
{{out}}
<pre>
|