Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct IntMod{N} <:Integer
- val::Int64
- function IntMod{N}(y) where {N}
- y%=N
- y>0 ? y=y : y = N+y
- return new(y)
- end
- end
- IntMod{N}(y::IntMod{N}) where {N} = y
- Base.:+(x::IntMod{N}, y::IntMod{N}) where {N} = IntMod{N}(x.val+y.val)
- Base.:-(x::IntMod{N}, y::IntMod{N}) where {N} = IntMod{N}(x.val-y.val)
- Base.:*(x::IntMod{N}, y::IntMod{N}) where {N} = IntMod{N}(x.val*y.val)
- Base.:/(x::IntMod{N}, y::IntMod{N}) where {N} = x*inv(y)
- Base.show(io::IO, x::IntMod{N}) where {N} = print(io, x.val," mod ", N)
- Modulus(x::IntMod{N}) where {N} = N
- macro intmod(x, N)
- return :(IntMod{$N}($x))
- end
- ## from Rosetta Code
- φ(n) = sum(1 for k in 1:n if gcd(n, k) == 1)
- is_prime(n) = φ(n) == n - 1
- @generated function Base.inv(x::IntMod{N}) where {N}
- if is_prime(N)
- return :(IntMod{N}(gcdx(x.val, $N)[2]))
- else
- return :(throw(DomainError(x, "N is not prime")))
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement