Advertisement
isaia_nisoli

Untitled

May 31st, 2020
2,405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 0.93 KB | None | 0 0
  1. struct IntMod{N} <:Integer
  2.     val::Int64
  3.     function IntMod{N}(y) where {N}
  4.         y%=N
  5.         y>0 ? y=y : y = N+y
  6.         return new(y)
  7.     end
  8. end
  9.  
  10. IntMod{N}(y::IntMod{N}) where {N} = y
  11.  
  12. Base.:+(x::IntMod{N}, y::IntMod{N}) where {N} = IntMod{N}(x.val+y.val)
  13. Base.:-(x::IntMod{N}, y::IntMod{N}) where {N} = IntMod{N}(x.val-y.val)
  14. Base.:*(x::IntMod{N}, y::IntMod{N}) where {N} = IntMod{N}(x.val*y.val)
  15. Base.:/(x::IntMod{N}, y::IntMod{N}) where {N} = x*inv(y)
  16. Base.show(io::IO, x::IntMod{N}) where {N} = print(io, x.val," mod ", N)
  17.  
  18. Modulus(x::IntMod{N}) where {N} = N
  19.  
  20. macro intmod(x, N)
  21.     return :(IntMod{$N}($x))
  22. end
  23.  
  24. ## from Rosetta Code
  25. φ(n) = sum(1 for k in 1:n if gcd(n, k) == 1)
  26. is_prime(n) = φ(n) == n - 1
  27.  
  28. @generated function Base.inv(x::IntMod{N}) where {N}
  29.     if is_prime(N)
  30.         return :(IntMod{N}(gcdx(x.val, $N)[2]))
  31.     else
  32.         return :(throw(DomainError(x, "N is not prime")))
  33.     end
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement