Require Export Arith.

(* 3-step induction principle as a function *)

Fixpoint mynat_ind 
(P:nat->Prop) (h0:P O)(h1:P (S O))(h2:P (S (S O)))
(hr:forall n:nat, P n -> P (S (S (S n))))(n:nat){struct n}:(P n) :=
match n return (P n) with
| O => h0
| S O => h1
| S (S O) =>h2
| S (S (S p)) => hr p (mynat_ind P h0 h1 h2 hr p)  
end.

(* hand-made proof of the induction principle *)

Lemma princ_ind : forall (P:nat->Prop),
 P 0 -> 
 P 1 ->
 P 2 ->
 (forall n:nat, P n -> P (S (S (S n)))) ->
 forall n:nat, P n .
Proof.
intros P H0 H1 H2 Hr n.
assert (P n /\ P(S n) /\ P(S(S n))).
induction n.
repeat split;assumption.
decompose [and] IHn; clear IHn.
repeat split.
 assumption.
 assumption.
 apply Hr;assumption.
tauto.
Qed.


Lemma coins : forall m :nat, exists i:nat, exists j:nat, 8+m=5*i+3*j.
Proof.
intros m; elim m using princ_ind.
exists 1.
exists 1.
simpl.
reflexivity.
exists 0.
exists 3.
simpl.
reflexivity.
exists 2.
exists 0.
simpl.
reflexivity.
intros n Hn.
elim Hn.
intros i Hi.
elim Hi.
intros j Hj.
exists i.
exists (S j).
simpl.
simpl in Hj.
rewrite Hj.
repeat rewrite <- plus_n_Sm.
reflexivity.
Qed.

(* With coins of $3 and $5, we can make all amount >= 8 *)
Theorem piece':forall m :nat, exists i:nat, exists j:nat, 8+m=5*i+3*j.
(* induction on m *)
intro m; elim m.
(* 8 = 5*1 + 3*1 *)
exists 1; exists 1.
simpl; auto.
(* Hypothèse d'induction Ind *)
intros n H'; elim H'; intros i E; elim E; intros j Ind; clear E H'.

rewrite <- plus_n_Sm; rewrite Ind.
(* At least one coin of $5 *)
destruct i.
(* At least one coin of $3 (j= (S j1)) ? *)
destruct j.
(* Impossible  *)
inversion Ind. (* or discriminate *)
(* At least two coins of $3 (j = (S (S j2)) ? *)
destruct j.
(* Impossible  *)
inversion Ind.
(* At least three coins of $3 (j = (S (S (S j3)))) *)
destruct j.
(* Impossible  *)
inversion Ind. (* discriminate *)
(* 3 coins of $3 are replaced by 2 coins of $5 *)
exists 2; exists j.
(* done for i=0 *)
ring.
(* We replace one coin of $5 with 2 of $3 (= +1) 3 *)
exists i; exists (j +2).
ring.
Qed.
