Skip to content

Commit a6cde76

Browse files
Merge pull request #20019 from JuliaLang/sk/modint
updates to the ModInt example
2 parents 184da04 + 8fbd76c commit a6cde76

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

examples/modint.jl renamed to examples/ModInts.jl

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,25 @@
33
module ModInts
44
export ModInt
55

6-
import Base: +, -, *
6+
import Base: +, -, *, /, inv
77

88
immutable ModInt{n} <: Integer
99
k::Int
1010
ModInt(k) = new(mod(k,n))
1111
end
1212

13-
-{n}(a::ModInt{n}) = ModInt{n}(-a.k)
13+
Base.show{n}(io::IO, k::ModInt{n}) =
14+
print(io, get(io, :compact, false) ? k.k : "$(k.k) mod $n")
15+
1416
+{n}(a::ModInt{n}, b::ModInt{n}) = ModInt{n}(a.k+b.k)
1517
-{n}(a::ModInt{n}, b::ModInt{n}) = ModInt{n}(a.k-b.k)
1618
*{n}(a::ModInt{n}, b::ModInt{n}) = ModInt{n}(a.k*b.k)
19+
-{n}(a::ModInt{n}) = ModInt{n}(-a.k)
1720

18-
Base.convert{n}(::Type{ModInt{n}}, i::Int) = ModInt{n}(i)
19-
Base.promote_rule{n}(::Type{ModInt{n}}, ::Type{Int}) = ModInt{n}
20-
21-
Base.show{n}(io::IO, k::ModInt{n}) = print(io, "$(k.k) mod $n")
22-
Base.showcompact(io::IO, k::ModInt) = print(io, k.k)
21+
inv{n}(a::ModInt{n}) = ModInt{n}(invmod(a.k, n))
22+
/{n}(a::ModInt{n}, b::ModInt{n}) = a*inv(b) # broaden for non-coprime?
2323

24-
Base.inv{n}(a::ModInt{n}) = ModInt{n}(invmod(a.k, n))
24+
Base.promote_rule{n}(::Type{ModInt{n}}, ::Type{Int}) = ModInt{n}
25+
Base.convert{n}(::Type{ModInt{n}}, i::Int) = ModInt{n}(i)
2526

2627
end # module

test/examples.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ a = rand(1:100,100)
99
include(joinpath(dir, "lru.jl"))
1010
include(joinpath(dir, "lru_test.jl"))
1111

12-
include(joinpath(dir, "modint.jl"))
12+
include(joinpath(dir, "ModInts.jl"))
1313
b = ModInts.ModInt{10}(2)
1414
c = ModInts.ModInt{10}(4)
1515
@test b + c == ModInts.ModInt{10}(6)

0 commit comments

Comments
 (0)