4
4
struct Factorization{T<: Integer } <: AbstractDict{T, Int}
5
5
pe:: Vector{Pair{T, Int}} # Prime-Exponent
6
6
7
- Factorization {T} () where {T<: Integer } = new {T} (Vector {Pair{T, Int}} ())
7
+ function Factorization {T} () where {T<: Integer }
8
+ # preallocates enough space that numbers smaller than 2310 won't need to resize
9
+ v = Vector {Pair{T, Int}} (undef, 4 )
10
+ empty! (v)
11
+ new {T} (v)
12
+ end
8
13
end
9
14
10
15
function Factorization {T} (d:: AbstractDict ) where T<: Integer
@@ -19,23 +24,39 @@ Base.convert(::Type{Factorization}, d::AbstractDict) = Factorization(d)
19
24
Base. iterate (f:: Factorization , state... ) = iterate (f. pe, state... )
20
25
21
26
function Base. get (f:: Factorization , p, default)
22
- found = searchsorted (f. pe, p, by= first)
23
- isempty (found) ?
24
- default :
25
- last (f. pe[first (found)])
27
+ found = searchsortedfirst (f. pe, p, by= first)
28
+ (found > length (f. pe) || first (f. pe[found])) != p ? default : last (f. pe[found])
26
29
end
27
30
28
31
Base. getindex (f:: Factorization , p:: Integer ) = get (f, p, 0 )
29
32
30
33
function Base. setindex! (f:: Factorization{T} , e:: Int , p:: Integer ) where T
31
- found = searchsorted (f. pe, p, by= first)
32
- if isempty (found)
33
- insert! (f. pe, first (found), T (p)=> e)
34
+ found = searchsortedfirst (f. pe, p, by= first)
35
+ if found > length (f. pe)
36
+ push! (f. pe, T (p)=> e)
37
+ elseif first (f. pe[found]) != p
38
+ insert! (f. pe, found, T (p)=> e)
39
+ else
40
+ f. pe[found] = T (p)=> e
41
+ end
42
+ f
43
+ end
44
+
45
+ """
46
+ impliments f[p] += e faster
47
+ """
48
+ function increment! (f:: Factorization{T} , e:: Int , p:: Integer ) where T
49
+ found = searchsortedfirst (f. pe, p, by= first)
50
+ if found > length (f. pe)
51
+ push! (f. pe, T (p)=> e)
52
+ elseif first (f. pe[found]) != p
53
+ insert! (f. pe, found, T (p)=> e)
34
54
else
35
- f. pe[first ( found) ] = T (p)=> e
55
+ f. pe[found] = T (p)=> ( last (f . pe[found]) + e)
36
56
end
37
57
f
38
58
end
59
+ increment! (f:: AbstractDict , e:: Int , p:: Integer ) = (f[p] = get (f, p, 0 ) + e)
39
60
40
61
Base. length (f:: Factorization ) = length (f. pe)
41
62
0 commit comments