|
| 1 | +import Base: mod, real, imag, reim, conj, promote_rule |
| 2 | + |
| 3 | +export GaussMod, AbstractMod |
| 4 | + |
| 5 | +# mod support for Gaussian integers until officially adopted into Base |
| 6 | +mod(z::Complex{<:Integer}, n::Integer) = Complex(mod(real(z), n), mod(imag(z), n)) |
| 7 | + |
| 8 | +""" |
| 9 | +`GaussMod{N,T}` is an alias of `Mod{N,Complex{T}}`. |
| 10 | +It is for computing Gaussian Modulus. |
| 11 | +""" |
| 12 | +const GaussMod{N,T} = Mod{N,Complex{T}} |
| 13 | +GaussMod{N}(x::T) where {N,T<:Integer} = Mod{N,Complex{T}}(x) |
| 14 | +GaussMod{N}(x::T) where {N,T<:Complex} = Mod{N,T}(x) |
| 15 | +Mod{N}(x::Complex{Rational{T}}) where {N,T} = Mod{N}(real(x)) + Mod{N}(imag(x)) * im |
| 16 | +Mod{N}(re::Integer, im::Integer) where {N} = Mod{N}(Complex(re, im)) |
| 17 | + |
| 18 | +reim(x::AbstractMod) = (real(x), imag(x)) |
| 19 | +real(x::Mod{N}) where {N} = Mod{N}(real(x.val)) |
| 20 | +imag(x::Mod{N}) where {N} = Mod{N}(imag(x.val)) |
| 21 | +conj(x::Mod{N}) where {N} = Mod{N}(conj(x.val)) |
| 22 | + |
| 23 | +# ARITHMETIC |
| 24 | +function (+)(x::GaussMod{N,T}, y::GaussMod{N,T}) where {N,T} |
| 25 | + xx = widen(x.val) |
| 26 | + yy = widen(y.val) |
| 27 | + zz = mod(xx + yy, N) |
| 28 | + return GaussMod{N,T}(zz) |
| 29 | +end |
| 30 | + |
| 31 | +(-)(x::GaussMod{N}) where {N} = Mod{N}(-x.val) |
| 32 | + |
| 33 | +function (*)(x::GaussMod{N,T}, y::GaussMod{N,T}) where {N,T} |
| 34 | + xx = widen(x.val) |
| 35 | + yy = widen(y.val) |
| 36 | + zz = mod(xx * yy, N) |
| 37 | + return GaussMod{N,T}(zz) |
| 38 | +end |
| 39 | + |
| 40 | +function inv(x::GaussMod{N}) where {N} |
| 41 | + try |
| 42 | + a, b = reim(x) |
| 43 | + bot = inv(a * a + b * b) |
| 44 | + aa = a * bot |
| 45 | + bb = -b * bot |
| 46 | + return aa + bb * im |
| 47 | + catch |
| 48 | + error("$x is not invertible") |
| 49 | + end |
| 50 | +end |
| 51 | + |
| 52 | +is_invertible(x::GaussMod) = is_invertible(real(x * x')) |
| 53 | +rand(::Type{GaussMod{N}}, args::Integer...) where {N} = rand(GaussMod{N,Int}, args...) |
0 commit comments