How to resolve the algorithm Negative base numbers step by step in the F# programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Negative base numbers step by step in the F# programming language

Table of Contents

Problem Statement

Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Negative base numbers step by step in the F# programming language

Source code in the fsharp programming language

//I provide 2 fuctions D2N takes a radix and an integer returning a sequence of integers
//                     N2D takse a radix and a sequence of integers returning an integer
//Note that the radix may be either positive or negative.  Nigel Galloway, May 10th., 2019
let D2N n g=if g=0 then seq[0] else Seq.unfold(fun g->let α,β=g/n,g%n in match (compare g 0,β) with
                                                                          (0,_)->None
                                                                         |(1,_) |(_,0)->Some(β,α)
                                                                         |_->Some(g-(α+1)*n,α+1)) g|>Seq.rev
let N2D n g=fst(Seq.foldBack(fun g (Σ,α)->(Σ+α*g,n*α)) g (0,1))


let t0,t146,t10,t15=D2N -13 0,D2N -3 146,D2N -2 10,D2N -10 15
Seq.iter(fun n->Seq.iter(printf "%d ")n; printfn "")[t0;t146;t10;t15]
Seq.iter(printfn "%d ")[N2D -13 t0;N2D -3 t146;N2D -2 t10;N2D -10 t15]


  

You may also check:How to resolve the algorithm Simple windowed application step by step in the Julia programming language
You may also check:How to resolve the algorithm Input loop step by step in the SNOBOL4 programming language
You may also check:How to resolve the algorithm I before E except after C step by step in the Draco programming language
You may also check:How to resolve the algorithm Range expansion step by step in the Prolog programming language
You may also check:How to resolve the algorithm String matching step by step in the 11l programming language