basebdigits[n_,b_]:= Module[ { m=n, l={}}, l= { Mod[ m,b]}; m=Quotient[n,b]; While[m>0, PrependTo[ l, Mod[m,b]]; m=Quotient[m,b]; ]; Return[l]];
basebdigits[ 137,10]
The first argument of Module is a list of variables used in the procedure. In
this case, we use
Instead of having the output as a list of digits, we may prefer to have it in
the standard
Exercise: Write a program to take the string form of a number and return its
value
Up to Procedural Programming
basebdigits[ 137,2]
m and l (for the list of digits). The variables can be initialized in the
first argument of Module, i.e.
within the braces. The program can also be written recursively because we are
computing the basebdigits of the quotient in the While loop. Here is another
program that
computes the base b digit expansion, this time, by calling itself with a
smaller argument.
newbasebdigits[n_,b_]:= Module[ {m=n, res= { Mod[n,b]}},
m= Quotient[ m,b];
If[ m>0,
res=Join[newbasebdigits[m,b],res]];
Return[res]]
newbasebdigits[137,2]
representation as a string, that is, 10001001 instead of { 1,0,0,0,1,0,0,1}.
This can
be done using the ToString command of Mathematica that will give the
string form of
an object, in this case, a string. We convert each digit to a String form and
then join
them using the StringJoin command. A list of String related commands is given
in the next
section.
basebform[n_,b_]:= StringJoin[
Map[ ToString[ #] &,
basebdigits[n,b]]]
basebform[ 137,2]
The Mathematica function Characters will return a list of characters
and the command
ToExpression will give the value of the string form of a digit.