How to resolve the algorithm Binary digits step by step in the Icon and Unicon programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Binary digits step by step in the Icon and Unicon programming language

Table of Contents

Problem Statement

Create and display the sequence of binary digits for a given   non-negative integer. The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Binary digits step by step in the Icon and Unicon programming language

Source code in the icon programming language

procedure main()
every i := 5 | 50 | 255 | 1285 | 9000 do
  write(i," = ",binary(i))
end

procedure binary(n)                      #: return bitstring for integer n
static CT, cm, cb
initial {
   CT := table()                         # cache table for results
   cm := 2 ^ (cb := 4)                   # (tunable) cache modulus & pad bits 
   }   

b := ""                                  # build reversed bit string
while n > 0 do {                         # use cached result ...
   if not (b ||:= \CT[1(i := n % cm, n /:= cm) ]) then {                     
      CT[j := i] := ""                   # ...or start new cache entry
      while j > 0 do 
         CT[i] ||:=  "01"[ 1(1+j % 2, j /:= 2 )]
      b ||:= CT[i] := left(CT[i],cb,"0") # finish cache with padding
      }
   }
return reverse(trim(b,"0"))              # nothing extraneous
end


  

You may also check:How to resolve the algorithm Variables step by step in the LotusScript programming language
You may also check:How to resolve the algorithm Zeckendorf arithmetic step by step in the C# programming language
You may also check:How to resolve the algorithm List comprehensions step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Morse code step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the Raven programming language