Population count

From Fōrmulæ wiki
Revision as of 09:59, 3 October 2019 by Admin (Talk | contribs) (Program)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This page is a solution to the task Population count in the Rosetta Code, written in Fōrmulæ.

Description (from Rosetta Code)

The population count is the number of 1s (ones) in the binary representation of a non-negative integer.

Population count is also known as pop count, popcount, sideways sum, and Hamming weight.

For example, 5 (which is 101 in binary) has a population count of 2.

Evil numbers are non-negative integers that have an even population count.

Odious numbers are positive integers that have an odd population count.

Task
  • Write a function (or routine) to return the population count of a non-negative integer.
  • All computation of the lists below should start with 0 (zero indexed).
  • Display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34 ∙∙∙ 329).
  • Display the 1st thirty evil numbers.
  • Display the 1st thirty odious numbers.
  • Display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also

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:

PopulationCountCode.png

The plot of the population count of the numbers 0..256:

PopulationCountPlotExample.png

Case 1. Displaying the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34 ∙∙∙ 329)

PopulationCountCase01.png

Case 2. Displaying 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:

PopulationCountCase02a.png

Calling the previous function with the criteria of being even numbers:

PopulationCountCase02b.png

Case 3. Displaying the 1st thirty odious numbers

Calling the previous function with the criteria of being odd numbers:

PopulationCountCase03.png