Population count: Difference between revisions
Content added Content deleted
(Added XPL0 example.) |
|||
Line 4,427: | Line 4,427: | ||
The first 30 odious numbers are: |
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 |
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> |
</pre> |
||