How to resolve the algorithm Population count step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Population count step by step in the OCaml programming language

Table of Contents

Problem Statement

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

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.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Population count step by step in the OCaml programming language

Source code in the ocaml programming language

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)


  

You may also check:How to resolve the algorithm Vigenère cipher step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the LSL programming language
You may also check:How to resolve the algorithm File extension is in extensions list step by step in the Haskell programming language
You may also check:How to resolve the algorithm Draw a clock step by step in the F# programming language
You may also check:How to resolve the algorithm Kaprekar numbers step by step in the C programming language