-
Notifications
You must be signed in to change notification settings - Fork 4
/
ModInt.swift
45 lines (45 loc) · 1.32 KB
/
ModInt.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
struct ModInt: AdditiveArithmetic, ExpressibleByIntegerLiteral, CustomStringConvertible, Hashable {
static var modulus: UInt! // FIXME: 問題に合わせて修正
let value: UInt
init(_ value: UInt) {
self.value = value % Self.modulus
}
init(_ value: Int) {
if value < 0 {
self.init(UInt(value % Int(Self.modulus) + Int(Self.modulus)))
} else {
self.init(UInt(value))
}
}
init(integerLiteral value: Int) {
self.init(value)
}
static func +(lhs: Self, rhs: Self) -> Self {
let r = lhs.value + rhs.value
if r < modulus {
return Self(r)
} else {
return Self(r - modulus)
}
}
static func -(lhs: Self, rhs: Self) -> Self {
if lhs.value < rhs.value {
return Self(lhs.value + modulus - rhs.value)
} else {
return Self(lhs.value - rhs.value)
}
}
static func *(lhs: Self, rhs: Self) -> Self {
Self((lhs.value * rhs.value) % modulus)
}
static func +=(lhs: inout Self, rhs: Self) {
lhs = lhs + rhs
}
static func -=(lhs: inout Self, rhs: Self) {
lhs = lhs - rhs
}
static func *=(lhs: inout Self, rhs: Self) {
lhs = lhs * rhs
}
var description: String { value.description }
}