| 1 |
From Coq Require Import Sumbool. |
| 2 |
From Coq Require Import Lia. |
| 3 |
From Coq Require Import NArith. |
| 4 |
From Coq Require Import PArith. |
| 5 |
From Coq Require Import List. |
| 6 |
From Coq.Program Require Import Wf. |
| 7 |
|
| 8 |
Local Open Scope positive_scope. |
| 9 |
|
| 10 |
(* given [n] and [d₀], returns, possibly, [d, v] where [d ≥ d₀] is small and [d * v = n] |
| 11 |
|
| 12 |
Precondition: [d₀] is either 2, or an odd number > 2 *) |
| 13 |
Definition find_N_factor (factor_val : N) (d0 : N) : option (N * N). |
| 14 |
Proof. |
| 15 |
refine (let (d', r) := N.div_eucl factor_val d0 in (* special-case the first one, which might be 2 *) |
| 16 |
if N.eqb 0 r |
| 17 |
then Some (d0, d') |
| 18 |
else |
| 19 |
let sfactor_val := N.sqrt factor_val in |
| 20 |
Fix |
| 21 |
(Acc_intro_generator (S (S (S (N.to_nat (N.div2 sfactor_val))))) (@N.gt_wf sfactor_val)) (fun _ => option (N * N)%type) |
| 22 |
(fun d find_N_factor |
| 23 |
=> let (d', r) := N.div_eucl factor_val d in |
| 24 |
if N.eqb 0 r |
| 25 |
then Some (d, d') |
| 26 |
else let d' := (d + 2)%N in |
| 27 |
if Sumbool.sumbool_of_bool (N.leb d' sfactor_val) |
| 28 |
then find_N_factor d' _ |
| 29 |
else None) |
| 30 |
(if N.eqb 2%N d0 then 3%N else (d0 + 2)%N)). |
| 31 |
{ subst sfactor_val d'. |
| 32 |
clear find_N_factor. |
| 33 |
let H := match goal with H : _ = true |- _ => H end in |
| 34 |
clear -H; |
| 35 |
abstract ( |
| 36 |
apply N.leb_le in H; |
| 37 |
split; try assumption; |
| 38 |
lia |
| 39 |
). } |
| 40 |
Defined. |
| 41 |
|
| 42 |
(* given [n] and [d₀], gives a list of factors of [n] which are ≥ d₀, lowest to highest *) |
| 43 |
Definition factorize' (n : N) : N -> list N. |
| 44 |
Proof. |
| 45 |
refine (Fix |
| 46 |
(Acc_intro_generator (S (S (S (S (N.to_nat (N.div2 (N.sqrt n))))))) N.lt_wf_0) (fun _ => N -> list N) |
| 47 |
(fun n factorize cur_max_factor |
| 48 |
=> _) |
| 49 |
n). |
| 50 |
refine match find_N_factor n cur_max_factor with |
| 51 |
| Some (d, n') => if Sumbool.sumbool_of_bool (n' <? n)%N |
| 52 |
then d :: factorize n' _ d |
| 53 |
else d :: n' :: nil |
| 54 |
| None => n::nil |
| 55 |
end. |
| 56 |
{ let H := match goal with H : _ = true |- _ => H end in |
| 57 |
clear -H; |
| 58 |
abstract ( |
| 59 |
apply N.ltb_lt in H; |
| 60 |
assumption |
| 61 |
). } |
| 62 |
Defined. |
| 63 |
|
| 64 |
Definition factorize (n : N) : list N := factorize' n 2%N. |
| 65 |
|
| 66 |
Definition factorize_or_fail (n:N) : option (list N) := |
| 67 |
let factors := factorize n in |
| 68 |
if N.eqb (List.fold_right N.mul 1%N factors) n then Some factors else None. |
| 69 |
Lemma product_factorize_or_fail (n:N) (factors:list N) |
| 70 |
(H:Logic.eq (factorize_or_fail n) (Some factors)) |
| 71 |
: Logic.eq (List.fold_right N.mul 1%N factors) n. |
| 72 |
Proof. cbv [factorize_or_fail] in H; destruct ((fold_right N.mul 1 (factorize n) =? n)%N) eqn:?; |
| 73 |
try apply N.eqb_eq; congruence. Qed. |