Library additions.Naive
Naïve and Monomorphic Functions for Computing Powers.
Exponentiation of integers
Require Import ZArith.
Open Scope Z_scope.
Module Z.
Fixpoint power (x:Z)(n:nat) :=
match n with
| 0%nat ⇒ 1
| S p ⇒ x × power x p
end.
Compute power 2 10.
Lemma power_S : ∀ (x:Z)(n:nat), power x (S n) = x × power x n.
Lemma power_of_plus (x:Z) :
∀ n p, power x (n + p) = power x n × power x p.
End Z.
Exponentiation modulo m
Module N_mod.
#[local] Open Scope N_scope.
Section m_fixed.
Variable m: N.
Definition mult_mod (x y : N) := (x × y) mod m.
Fixpoint power (x: N) (n : nat) : N :=
match n with
| 0%nat ⇒ 1 mod m
| S p ⇒ mult_mod x (power x p)
end.
End m_fixed.
End N_mod.
Compute N_mod.power 14555553%N 5689%N 27.
= 9086410
: N
Exponentiation of matrices
Module M2.
Section Definitions.
Variables (A: Type)
(zero one : A)
(plus mult : A → A → A).
Variable rt : semi_ring_theory zero one plus mult (@eq A).
Add Ring Aring : rt.
Notation "0" := zero.
Notation "1" := one.
Notation "x + y" := (plus x y).
Notation "x * y " := (mult x y).
Structure t : Type := mat{c00 : A; c01 : A;
c10 : A; c11 : A}.
Definition Id2 : t := mat 1 0 0 1.
Definition M2_mult (M M':t) : t :=
mat (c00 M × c00 M' + c01 M × c10 M')
(c00 M × c01 M' + c01 M × c11 M')
(c10 M × c00 M' + c11 M × c10 M')
(c10 M × c01 M' + c11 M × c11 M').
Infix "**" := M2_mult (at level 40, left associativity).
Fixpoint power (M : t) (n : nat) : t :=
match n with
| 0%nat ⇒ Id2
| S p ⇒ M ** (power M p)
end.
Section Definitions.
Variables (A: Type)
(zero one : A)
(plus mult : A → A → A).
Variable rt : semi_ring_theory zero one plus mult (@eq A).
Add Ring Aring : rt.
Notation "0" := zero.
Notation "1" := one.
Notation "x + y" := (plus x y).
Notation "x * y " := (mult x y).
Structure t : Type := mat{c00 : A; c01 : A;
c10 : A; c11 : A}.
Definition Id2 : t := mat 1 0 0 1.
Definition M2_mult (M M':t) : t :=
mat (c00 M × c00 M' + c01 M × c10 M')
(c00 M × c01 M' + c01 M × c11 M')
(c10 M × c00 M' + c11 M × c10 M')
(c10 M × c01 M' + c11 M × c11 M').
Infix "**" := M2_mult (at level 40, left associativity).
Fixpoint power (M : t) (n : nat) : t :=
match n with
| 0%nat ⇒ Id2
| S p ⇒ M ** (power M p)
end.
The ring tactic, applied to inhabitants of type A, allows us to prove associativity of matrix multiplication, then a law of distributivity of power upon **
Lemma Id2_neutral : ∀ M:t, Id2 ** M = M.
Lemma M2_mult_assoc : ∀ M M' M'':t, M ** (M' ** M'') =
(M ** M') ** M''.
Lemma power_of_plus (M:t) :
∀ n p, power M (n + p) = power M n ** power M p.
End Definitions.
End M2.
Definition fibonacci (n:nat) :=
M2.c00 N (M2.power N 0%N 1%N Nplus Nmult (M2.mat _ 1 1 1 0)%N n).