mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2025-12-06 03:05:28 -05:00
pow pow pow
Voilà un petit commit en annexe. -- Bernardo >From f11b65e1d282467d2dca8612a6fafa718c66e022 Mon Sep 17 00:00:00 2001 From: Bernardo Freitas Paulo da Costa <bernardo.da-costa@m4x.org> Date: Thu, 30 Apr 2015 10:24:21 -0300 Subject: [PATCH] Add CCInt.pow Binary exponentiation for positive numbers.
This commit is contained in:
parent
531134d754
commit
84e77fddcf
2 changed files with 24 additions and 0 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue