Re: arithmetic operations on very large integers in different bases
- From: heiner.marxen@xxxxxxxx (Heiner Marxen)
- Date: Tue, 1 Aug 2006 18:16:59 +0000 (UTC)
In article <eadsq3$mu4$1@xxxxxxxxxxxxxxxxxxxxxxxx>,
oopsnic@xxxxxxxxx writes:
Hi guys,
I am trying to write a program in ML (know how to write in C trying to
learn it in SML) that can perform arithmetic operations on 2 integers
recursively without using library functions in differenet bases.
e.g.
List1 = contains digits of 1st VL integer
List2 = contains digits of 2nd VL integer
List3 = contains digits of end result
user input (* Also have problem here, how to get input from user*)
sign
|---------------------digit-----------------| base
Enter first digit: [+/-] 12392183873947294334234234 [36]
Enter 2nd digit: [+/-] 789237498797692302323443243243245 [36]
result: plus(L1, L2)
fun plus([H1::T1], [H2::T2], Carry, [H3::T3])
H3 = (H1 + H2 + Carry) mod 10 (* This is where the base comes in and
not certain if this is the right way of implementing it*)
C2 = (H1+H2+C) div 10
plus(T1, T2, C2, T3)
Can someone please help me with implementation and elaborate the
precise implementation for the above?
I would start with a layer for nonnegative numbers (natural numbers),
and then augment with a sign and a set of functions to map signed
operations to unsigned ones.
For unsigned addition here an example implementation:
val base = 10;
fun setC(0) = []
| setC(c) = (c mod base) :: setC(c div base) (* [c] for small c < base *)
;
fun addC( x , 0) = x
| addC( [] , c) = setC(c)
| addC(h::t, c) = ((h+c) mod base) :: addC(t, (h+c) div base)
;
fun add( [] , [] , c ) = setC(c)
| add( [] , y , c ) = addC(y,c) (* add([0],y,c) *)
| add( x , [] , c ) = addC(x,c) (* add(x,[0],c) *)
| add( xh::xt, yh::yt, c ) =
let
val sum = xh + yh + c;
val dig = sum mod base;
val c' = sum div base;
in
dig :: add(xt, yt, c')
end
fun plus(x,y) = add(x,y,0);
If you cannot fix the base outside the numbers, you will have to think
about, how to determine the base of the result... I've never done so.
BTW: are you aware of "IntInf.int"?
--
Heiner Marxen http://www.drb.insel.de/~heiner/
.
- References:
- Prev by Date: Re: arithmetic operations on very large integers in different bases
- Next by Date: Int.precision & Word.wordSize
- Previous by thread: Re: arithmetic operations on very large integers in different bases
- Next by thread: Re: arithmetic operations on very large integers in different bases
- Index(es):
Relevant Pages
|
Loading