Script Library: 1218 scripts
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

Discussion posts for script bignumbers.r

1
guest2
27-Mar-2007 17:16
Edited:
guest2
27-Mar-2007 17:19
hello
i had a look on your script.
yes it works,  but it is very slow even if the code was optimized.

there is better ways, search on Internet for some good theories:

and have a look on what follows:

[code]
mul: func [n1 n2 /local tmp res len a b c d][

 ; n1 * n2 can be decomposed in four numbers, following the formula 
 (a + b) * (c + d).

 ; The goal is to decompose them into smaller numbers (recursivly) 
 until we can use the native mult operation
	; of rebol.

 ; Then, the big number is rebuild by addition and concatenation of 
 intermediate results. 
	len: max length? n1 length? n2
 if len < 5 [return to string! (to integer! n1) * to integer! n2]
	res: cp ""
	if 0 = len: min 4 min length? n1 length? n2 [return ""]
	a: cp/part n1 (length? n1) - len
	b: at n1 (length? n1) - len + 1
	c: cp/part n2 (length? n2) - len
	d: at n2 (length? n2) - len + 1
	res: mul b d
	tmp: add mul a d mul c b

 either len < length? res [tmp: add tmp cp/part res (length? res) 
 - len][insert/dup res "0" len - length? res]
	res: append tmp at res (length? res) - len + 1
	tmp: mul a c
	len: len * 2

 either len < length? res [tmp: add tmp cp/part res (length? res) 
 - len][insert/dup res "0" len - length? res]
	append tmp at res (length? res) - len  + 1
]

add: func [n1 n2 /local len tmp res a b c d][

 ; same as above, n1 and n2 are decomposed in smaller numbers, recursivly 
 until Rebol can operate them nativly.

 if 10 > max length? n1 length? n2 [return to string! (to integer! 
 n1) + to integer! n2]

 if 0 = len: min 9 min length? n1 length? n2 [return either empty? 
 n1 [n2][n1]]
	a: cp/part n1 (length? n1) - len
	b: at n1 (length? n1) - len + 1
	c: cp/part n2 (length? n2) - len
	d: at n2 (length? n2) - len + 1
	res: add b d
	tmp: add a c

 either len < length? res [tmp: add tmp "1" remove res][insert/dup 
 res "0" len - length? res]
	append tmp res
]
[/code]