diff --git a/025-factorize.dfy b/025-factorize.dfy new file mode 100644 index 0000000..ba4f214 --- /dev/null +++ b/025-factorize.dfy @@ -0,0 +1,40 @@ +function prod(s: seq) : int { + if |s| == 0 then 1 else prod(s[..|s| - 1]) * s[|s| - 1] +} + +method factorize(n: nat) returns (factors: seq) + requires n > 0 + ensures prod(factors) == n +{ + factors := []; + ghost var taken := 1; + var cur := n; + var i := 2; + while i * i <= cur + invariant prod(factors) == taken + invariant taken * cur == n + invariant cur >= 1 + { + ghost var pre := cur; + ghost var temp := 1; + while cur % i == 0 + invariant cur >= 1 + invariant temp * cur == pre + invariant prod(factors) == taken * temp + decreases cur - 1 + { + factors := factors + [i]; + + cur := cur / i; + temp := temp * i; + assert 2 <= i && 2 * cur <= i * cur; + } + taken := taken * temp; + i := i + 1; + } + if cur > 1 { + factors := factors + [cur]; + taken := taken * cur; + } + assert taken == n; +} \ No newline at end of file diff --git a/README.md b/README.md index fde3fd2..e273db8 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Current status: - [ ] 22. filter_integers - ill-typed - [x] 23. strlen - [x] 24. largest_divisor -- [ ] 25. factorize +- [x] 25. factorize - [x] 26. remove_duplicates - [x] 27. flip_case - [ ] 28. concatenate diff --git a/REMAINING.md b/REMAINING.md index 7288c22..c08b502 100644 --- a/REMAINING.md +++ b/REMAINING.md @@ -3,7 +3,6 @@ Current status: ## Priority -- [ ] 25. factorize - [ ] 147. get_max_triples ## Other