From 84e77fddcffa747c9a865134931ecb1f0e99fa9e Mon Sep 17 00:00:00 2001 From: Bernardo da Costa Date: Thu, 30 Apr 2015 10:44:54 -0300 Subject: [PATCH] pow pow pow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit VoilĂ  un petit commit en annexe. -- Bernardo >From f11b65e1d282467d2dca8612a6fafa718c66e022 Mon Sep 17 00:00:00 2001 From: Bernardo Freitas Paulo da Costa Date: Thu, 30 Apr 2015 10:24:21 -0300 Subject: [PATCH] Add CCInt.pow Binary exponentiation for positive numbers. --- src/core/CCInt.ml | 19 +++++++++++++++++++ src/core/CCInt.mli | 5 +++++ 2 files changed, 24 insertions(+) diff --git a/src/core/CCInt.ml b/src/core/CCInt.ml index 4a7bbf1f..1c177c1a 100644 --- a/src/core/CCInt.ml +++ b/src/core/CCInt.ml @@ -39,6 +39,25 @@ let sign i = let neg i = -i +let pow a b = + let rec aux acc = function + | 1 -> acc + | n -> + if n mod 2 = 0 + then aux (acc*acc) (n/2) + else acc * (aux (acc*acc) (n/2)) + in + match b with + | 0 -> if a = 0 then raise (Invalid_argument "Undefined value 0^0") else 1 + | b when b < 0 -> raise (Invalid_argument "pow: can't raise int to negative power") + | b -> aux a b + +(*$T + pow 2 10 = 1024 + pow 2 15 = 32768 + pow 10 5 = 100000 +*) + type 'a printer = Buffer.t -> 'a -> unit type 'a formatter = Format.formatter -> 'a -> unit type 'a random_gen = Random.State.t -> 'a diff --git a/src/core/CCInt.mli b/src/core/CCInt.mli index 12a9040c..8b9a3eaa 100644 --- a/src/core/CCInt.mli +++ b/src/core/CCInt.mli @@ -41,6 +41,11 @@ val neg : t -> t (** [neg i = - i] @since 0.5 *) +val pow : t -> t -> t +(** [pow a b = a^b] for positive integers [a] and [b]. + raises [Invalid_argument] if [a = b = 0] or [b] < 0. + @since NEXT_RELEASE *) + type 'a printer = Buffer.t -> 'a -> unit type 'a formatter = Format.formatter -> 'a -> unit type 'a random_gen = Random.State.t -> 'a