PageRenderTime 91ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/bigint.ml

https://bitbucket.org/makarius/coq-clone
OCaml | 409 lines | 303 code | 55 blank | 51 comment | 128 complexity | 60dad722116d5c56446e78dbc2152f65 MD5 | raw file
Possible License(s): LGPL-2.1
  1. (************************************************************************)
  2. (* v * The Coq Proof Assistant / The Coq Development Team *)
  3. (* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010 *)
  4. (* \VV/ **************************************************************)
  5. (* // * This file is distributed under the terms of the *)
  6. (* * GNU Lesser General Public License Version 2.1 *)
  7. (************************************************************************)
  8. (*i*)
  9. open Pp
  10. (*i*)
  11. (***************************************************)
  12. (* Basic operations on (unbounded) integer numbers *)
  13. (***************************************************)
  14. (* An integer is canonically represented as an array of k-digits blocs.
  15. 0 is represented by the empty array and -1 by the singleton [|-1|].
  16. The first bloc is in the range ]0;10^k[ for positive numbers.
  17. The first bloc is in the range ]-10^k;-1[ for negative ones.
  18. All other blocs are numbers in the range [0;10^k[.
  19. Negative numbers are represented using 2's complementation. For instance,
  20. with 4-digits blocs, [-9655;6789] denotes -96543211
  21. *)
  22. (* The base is a power of 10 in order to facilitate the parsing and printing
  23. of numbers in digital notation.
  24. All functions, to the exception of to_string and of_string should work
  25. with an arbitrary base, even if not a power of 10.
  26. In practice, we set k=4 so that no overflow in ocaml machine words
  27. (i.e. the interval [-2^30;2^30-1]) occur when multiplying two
  28. numbers less than (10^k)
  29. *)
  30. (* The main parameters *)
  31. let size =
  32. let rec log10 n = if n < 10 then 0 else 1 + log10 (n / 10) in
  33. (log10 max_int) / 2
  34. let format_size =
  35. (* How to parametrize a printf format *)
  36. if size = 4 then Printf.sprintf "%04d"
  37. else fun n ->
  38. let rec aux j l n =
  39. if j=size then l else aux (j+1) (string_of_int (n mod 10) :: l) (n/10)
  40. in String.concat "" (aux 0 [] n)
  41. (* The base is 10^size *)
  42. let base =
  43. let rec exp10 = function 0 -> 1 | n -> 10 * exp10 (n-1) in exp10 size
  44. (* Basic numbers *)
  45. let zero = [||]
  46. let neg_one = [|-1|]
  47. (* Sign of an integer *)
  48. let is_strictly_neg n = n<>[||] && n.(0) < 0
  49. let is_strictly_pos n = n<>[||] && n.(0) > 0
  50. let is_neg_or_zero n = n=[||] or n.(0) < 0
  51. let is_pos_or_zero n = n=[||] or n.(0) > 0
  52. let normalize_pos n =
  53. let k = ref 0 in
  54. while !k < Array.length n & n.(!k) = 0 do incr k done;
  55. Array.sub n !k (Array.length n - !k)
  56. let normalize_neg n =
  57. let k = ref 1 in
  58. while !k < Array.length n & n.(!k) = base - 1 do incr k done;
  59. let n' = Array.sub n !k (Array.length n - !k) in
  60. if Array.length n' = 0 then [|-1|] else (n'.(0) <- n'.(0) - base; n')
  61. let rec normalize n =
  62. if Array.length n = 0 then n else
  63. if n.(0) = -1 then normalize_neg n else normalize_pos n
  64. let neg m =
  65. if m = zero then zero else
  66. let n = Array.copy m in
  67. let i = ref (Array.length m - 1) in
  68. while !i > 0 & n.(!i) = 0 do decr i done;
  69. if !i > 0 then begin
  70. n.(!i) <- base - n.(!i); decr i;
  71. while !i > 0 do n.(!i) <- base - 1 - n.(!i); decr i done;
  72. n.(0) <- - n.(0) - 1;
  73. if n.(0) < -1 then (n.(0) <- n.(0) + base; Array.append [| -1 |] n) else
  74. if n.(0) = - base then (n.(0) <- 0; Array.append [| -1 |] n)
  75. else normalize n
  76. end else (n.(0) <- - n.(0); n)
  77. let push_carry r j =
  78. let j = ref j in
  79. while !j > 0 & r.(!j) < 0 do
  80. r.(!j) <- r.(!j) + base; decr j; r.(!j) <- r.(!j) - 1
  81. done;
  82. while !j > 0 & r.(!j) >= base do
  83. r.(!j) <- r.(!j) - base; decr j; r.(!j) <- r.(!j) + 1
  84. done;
  85. if r.(0) >= base then (r.(0) <- r.(0) - base; Array.append [| 1 |] r)
  86. else if r.(0) < -base then (r.(0) <- r.(0) + 2*base; Array.append [| -2 |] r)
  87. else if r.(0) = -base then (r.(0) <- 0; Array.append [| -1 |] r)
  88. else normalize r
  89. let add_to r a j =
  90. if a = zero then r else begin
  91. for i = Array.length r - 1 downto j+1 do
  92. r.(i) <- r.(i) + a.(i-j);
  93. if r.(i) >= base then (r.(i) <- r.(i) - base; r.(i-1) <- r.(i-1) + 1)
  94. done;
  95. r.(j) <- r.(j) + a.(0);
  96. push_carry r j
  97. end
  98. let add n m =
  99. let d = Array.length n - Array.length m in
  100. if d > 0 then add_to (Array.copy n) m d else add_to (Array.copy m) n (-d)
  101. let sub_to r a j =
  102. if a = zero then r else begin
  103. for i = Array.length r - 1 downto j+1 do
  104. r.(i) <- r.(i) - a.(i-j);
  105. if r.(i) < 0 then (r.(i) <- r.(i) + base; r.(i-1) <- r.(i-1) - 1)
  106. done;
  107. r.(j) <- r.(j) - a.(0);
  108. push_carry r j
  109. end
  110. let sub n m =
  111. let d = Array.length n - Array.length m in
  112. if d >= 0 then sub_to (Array.copy n) m d
  113. else let r = neg m in add_to r n (Array.length r - Array.length n)
  114. let rec mult m n =
  115. if m = zero or n = zero then zero else
  116. let l = Array.length m + Array.length n in
  117. let r = Array.create l 0 in
  118. for i = Array.length m - 1 downto 0 do
  119. for j = Array.length n - 1 downto 0 do
  120. let p = m.(i) * n.(j) + r.(i+j+1) in
  121. let (q,s) =
  122. if p < 0
  123. then (p + 1) / base - 1, (p + 1) mod base + base - 1
  124. else p / base, p mod base in
  125. r.(i+j+1) <- s;
  126. if q <> 0 then r.(i+j) <- r.(i+j) + q;
  127. done
  128. done;
  129. normalize r
  130. let rec less_than_same_size m n i j =
  131. i < Array.length m &&
  132. (m.(i) < n.(j) or (m.(i) = n.(j) && less_than_same_size m n (i+1) (j+1)))
  133. let less_than m n =
  134. if is_strictly_neg m then
  135. is_pos_or_zero n or Array.length m > Array.length n
  136. or (Array.length m = Array.length n && less_than_same_size m n 0 0)
  137. else
  138. is_strictly_pos n && (Array.length m < Array.length n or
  139. (Array.length m = Array.length n && less_than_same_size m n 0 0))
  140. let equal m n = (m = n)
  141. let less_than_shift_pos k m n =
  142. (Array.length m - k < Array.length n)
  143. or (Array.length m - k = Array.length n && less_than_same_size m n k 0)
  144. let rec can_divide k m d i =
  145. (i = Array.length d) or
  146. (m.(k+i) > d.(i)) or
  147. (m.(k+i) = d.(i) && can_divide k m d (i+1))
  148. (* computes m - d * q * base^(|m|-k) in-place on positive numbers *)
  149. let sub_mult m d q k =
  150. if q <> 0 then
  151. for i = Array.length d - 1 downto 0 do
  152. let v = d.(i) * q in
  153. m.(k+i) <- m.(k+i) - v mod base;
  154. if m.(k+i) < 0 then (m.(k+i) <- m.(k+i) + base; m.(k+i-1) <- m.(k+i-1) -1);
  155. if v >= base then m.(k+i-1) <- m.(k+i-1) - v / base;
  156. done
  157. let euclid m d =
  158. let isnegm, m =
  159. if is_strictly_neg m then (-1),neg m else 1,Array.copy m in
  160. let isnegd, d = if is_strictly_neg d then (-1),neg d else 1,d in
  161. if d = zero then raise Division_by_zero;
  162. let q,r =
  163. if less_than m d then (zero,m) else
  164. let ql = Array.length m - Array.length d in
  165. let q = Array.create (ql+1) 0 in
  166. let i = ref 0 in
  167. while not (less_than_shift_pos !i m d) do
  168. if m.(!i)=0 then incr i else
  169. if can_divide !i m d 0 then begin
  170. let v =
  171. if Array.length d > 1 && d.(0) <> m.(!i) then
  172. (m.(!i) * base + m.(!i+1)) / (d.(0) * base + d.(1) + 1)
  173. else
  174. m.(!i) / d.(0) in
  175. q.(!i) <- q.(!i) + v;
  176. sub_mult m d v !i
  177. end else begin
  178. let v = (m.(!i) * base + m.(!i+1)) / (d.(0) + 1) in
  179. q.(!i) <- q.(!i) + v / base;
  180. sub_mult m d (v / base) !i;
  181. q.(!i+1) <- q.(!i+1) + v mod base;
  182. if q.(!i+1) >= base then
  183. (q.(!i+1) <- q.(!i+1)-base; q.(!i) <- q.(!i)+1);
  184. sub_mult m d (v mod base) (!i+1)
  185. end
  186. done;
  187. (normalize q, normalize m) in
  188. (if isnegd * isnegm = -1 then neg q else q),
  189. (if isnegm = -1 then neg r else r)
  190. (* Parsing/printing ordinary 10-based numbers *)
  191. let of_string s =
  192. let isneg = String.length s > 1 & s.[0] = '-' in
  193. let n = if isneg then 1 else 0 in
  194. let d = ref n in
  195. while !d < String.length s && s.[!d] = '0' do incr d done;
  196. if !d = String.length s then zero else
  197. let r = (String.length s - !d) mod size in
  198. let h = String.sub s (!d) r in
  199. if !d = String.length s - 1 && isneg && h="1" then neg_one else
  200. let e = if h<>"" then 1 else 0 in
  201. let l = (String.length s - !d) / size in
  202. let a = Array.create (l + e + n) 0 in
  203. if isneg then begin
  204. a.(0) <- (-1);
  205. let carry = ref 0 in
  206. for i=l downto 1 do
  207. let v = int_of_string (String.sub s ((i-1)*size + !d +r) size)+ !carry in
  208. if v <> 0 then (a.(i+e)<- base - v; carry := 1) else carry := 0
  209. done;
  210. if e=1 then a.(1) <- base - !carry - int_of_string h;
  211. end
  212. else begin
  213. if e=1 then a.(0) <- int_of_string h;
  214. for i=1 to l do
  215. a.(i+e-1) <- int_of_string (String.sub s ((i-1)*size + !d + r) size)
  216. done
  217. end;
  218. a
  219. let to_string_pos sgn n =
  220. if Array.length n = 0 then "0" else
  221. sgn ^
  222. String.concat ""
  223. (string_of_int n.(0) :: List.map format_size (List.tl (Array.to_list n)))
  224. let to_string n =
  225. if is_strictly_neg n then to_string_pos "-" (neg n)
  226. else to_string_pos "" n
  227. (******************************************************************)
  228. (* Optimized operations on (unbounded) integer numbers *)
  229. (* integers smaller than base are represented as machine integers *)
  230. (******************************************************************)
  231. type bigint = Obj.t
  232. let ints_of_int n =
  233. if n >= base then [| n / base; n mod base |]
  234. else if n <= - base then [| n / base - 1; n mod base + base |]
  235. else if n = 0 then [| |] else [| n |]
  236. let big_of_int n =
  237. if n >= base then Obj.repr [| n / base; n mod base |]
  238. else if n <= - base then Obj.repr [| n / base - 1; n mod base + base |]
  239. else Obj.repr n
  240. let big_of_ints n =
  241. let n = normalize n in
  242. if n = zero then Obj.repr 0 else
  243. if Array.length n = 1 then Obj.repr n.(0) else
  244. Obj.repr n
  245. let coerce_to_int = (Obj.magic : Obj.t -> int)
  246. let coerce_to_ints = (Obj.magic : Obj.t -> int array)
  247. let ints_of_z n =
  248. if Obj.is_int n then ints_of_int (coerce_to_int n)
  249. else coerce_to_ints n
  250. let app_pair f (m, n) =
  251. (f m, f n)
  252. let add m n =
  253. if Obj.is_int m & Obj.is_int n
  254. then big_of_int (coerce_to_int m + coerce_to_int n)
  255. else big_of_ints (add (ints_of_z m) (ints_of_z n))
  256. let sub m n =
  257. if Obj.is_int m & Obj.is_int n
  258. then big_of_int (coerce_to_int m - coerce_to_int n)
  259. else big_of_ints (sub (ints_of_z m) (ints_of_z n))
  260. let mult m n =
  261. if Obj.is_int m & Obj.is_int n
  262. then big_of_int (coerce_to_int m * coerce_to_int n)
  263. else big_of_ints (mult (ints_of_z m) (ints_of_z n))
  264. let euclid m n =
  265. if Obj.is_int m & Obj.is_int n
  266. then app_pair big_of_int
  267. (coerce_to_int m / coerce_to_int n, coerce_to_int m mod coerce_to_int n)
  268. else app_pair big_of_ints (euclid (ints_of_z m) (ints_of_z n))
  269. let less_than m n =
  270. if Obj.is_int m & Obj.is_int n
  271. then coerce_to_int m < coerce_to_int n
  272. else less_than (ints_of_z m) (ints_of_z n)
  273. let neg n =
  274. if Obj.is_int n then big_of_int (- (coerce_to_int n))
  275. else big_of_ints (neg (ints_of_z n))
  276. let of_string m = big_of_ints (of_string m)
  277. let to_string m = to_string (ints_of_z m)
  278. let zero = big_of_int 0
  279. let one = big_of_int 1
  280. let sub_1 n = sub n one
  281. let add_1 n = add n one
  282. let two = big_of_int 2
  283. let mult_2 n = add n n
  284. let div2_with_rest n =
  285. let (q,b) = euclid n two in
  286. (q, b = one)
  287. let is_strictly_neg n = is_strictly_neg (ints_of_z n)
  288. let is_strictly_pos n = is_strictly_pos (ints_of_z n)
  289. let is_neg_or_zero n = is_neg_or_zero (ints_of_z n)
  290. let is_pos_or_zero n = is_pos_or_zero (ints_of_z n)
  291. let pr_bigint n = str (to_string n)
  292. (* spiwack: computes n^m *)
  293. (* The basic idea of the algorithm is that n^(2m) = (n^2)^m *)
  294. (* In practice the algorithm performs :
  295. k*n^0 = k
  296. k*n^(2m) = k*(n*n)^m
  297. k*n^(2m+1) = (n*k)*(n*n)^m *)
  298. let pow =
  299. let rec pow_aux odd_rest n m = (* odd_rest is the k from above *)
  300. if is_neg_or_zero m then
  301. odd_rest
  302. else
  303. let (quo,rem) = div2_with_rest m in
  304. pow_aux
  305. ((* [if m mod 2 = 1]*)
  306. if rem then
  307. mult n odd_rest
  308. else
  309. odd_rest )
  310. (* quo = [m/2] *)
  311. (mult n n) quo
  312. in
  313. pow_aux one
  314. (* Testing suite *)
  315. let check () =
  316. let numbers = [
  317. "1";"2";"99";"100";"101";"9999";"10000";"10001";
  318. "999999";"1000000";"1000001";"99999999";"100000000";"100000001";
  319. "1234";"5678";"12345678";"987654321";
  320. "-1";"-2";"-99";"-100";"-101";"-9999";"-10000";"-10001";
  321. "-999999";"-1000000";"-1000001";"-99999999";"-100000000";"-100000001";
  322. "-1234";"-5678";"-12345678";"-987654321";"0"
  323. ]
  324. in
  325. let eucl n m =
  326. let n' = abs_float n and m' = abs_float m in
  327. let q' = floor (n' /. m') in let r' = n' -. m' *. q' in
  328. (if n *. m < 0. & q' <> 0. then -. q' else q'),
  329. (if n < 0. then -. r' else r') in
  330. let round f = floor (abs_float f +. 0.5) *. (if f < 0. then -1. else 1.) in
  331. let i = ref 0 in
  332. let compare op n n' =
  333. incr i;
  334. let s = Printf.sprintf "%30s" (to_string n) in
  335. let s' = Printf.sprintf "% 30.0f" (round n') in
  336. if s <> s' then Printf.printf "%s: %s <> %s\n" op s s' in
  337. List.iter (fun a -> List.iter (fun b ->
  338. let n = of_string a and m = of_string b in
  339. let n' = float_of_string a and m' = float_of_string b in
  340. let a = add n m and a' = n' +. m' in
  341. let s = sub n m and s' = n' -. m' in
  342. let p = mult n m and p' = n' *. m' in
  343. let q,r = try euclid n m with Division_by_zero -> zero,zero
  344. and q',r' = eucl n' m' in
  345. compare "+" a a';
  346. compare "-" s s';
  347. compare "*" p p';
  348. compare "/" q q';
  349. compare "%" r r') numbers) numbers;
  350. Printf.printf "%i tests done\n" !i