Advertisement
Guest User

p

a guest
Dec 18th, 2018
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 2.25 KB | None | 0 0
  1. (** Power function implementations for built-in integers *)
  2.  
  3. #use "builtin";;
  4. #use "basic_arithmetics";;
  5.  
  6. (* Naive and fast exponentiation ; already implemented in-class.
  7.  *)
  8.  
  9. (** Naive power function. Linear complexity
  10.     @param x base
  11.     @param n exponent
  12.  *)
  13. let pow x n = (
  14.     let rec _pow ?(i=1) x n = (
  15.         if
  16.           n = 0 then 1
  17.         else
  18.           if i = n then
  19.               x
  20.           else
  21.               x*(_pow ~i:(i+1) x n )
  22.     ) in
  23.         _pow x n
  24. );;
  25.  
  26. (** Fast integer exponentiation function. Logarithmic complexity.
  27.     @param x base
  28.     @param n exponent
  29.  *)
  30. let power x n = (
  31.     let rec _power num =(function
  32.         (*This function was in the seminary, so it is likely that other people will have the same*)
  33.       | 0 -> 1
  34.       | 1 -> num
  35.       | n ->
  36.         let b = _power num (n / 2) in
  37.             b * b * (if n mod 2 = 0 then 1 else num)
  38.     ) in
  39.         _power x n
  40. );;
  41.  
  42. (* Modular expnonentiation ; modulo a given natural number smaller
  43.    max_int we never have integer-overflows if implemented properly.
  44.  *)
  45.  
  46. (** Fast modular exponentiation function. Logarithmic complexity.
  47.     @param x base
  48.     @param n exponent
  49.     @param m modular base
  50.  *)
  51. let mod_power x n m = (
  52.     let
  53.       rec _mod_power num n =(
  54.         match n with
  55.           | 0 -> 1
  56.           | 1 -> num
  57.           | x ->
  58.             let b = (_mod_power num (x / 2)) in
  59.                 modulo (b * b * (if x mod 2 = 0 then 1 else num)) m
  60.       )
  61.     in
  62.       modulo (_mod_power x n) m
  63. );;
  64.  
  65. (* Making use of Fermat Little Theorem for very quick exponentation
  66.    modulo prime number.
  67.  *)
  68.  
  69. (** Fast modular exponentiation function mod prime. Logarithmic complexity.
  70.     It makes use of the Little Fermat Theorem.
  71.     @param x base
  72.     @param n exponent
  73.     @param p prime modular base
  74.  *)
  75. let prime_mod_power x n p = (
  76.   if x = 0 then
  77.     0
  78.   else
  79.     let
  80.       rec _prime_mod_power num n =(
  81.         match n with
  82.           | 0 -> 1
  83.           | 1 -> num
  84.           | x when x = p-1 -> 1
  85.           | x ->
  86.             let b = (_prime_mod_power num (x / 2)) in
  87.                 modulo (b * b * (if x mod 2 = 0 then 1 else num)) p
  88.         )
  89.       in
  90.         modulo (_prime_mod_power x n) p
  91. );;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement