Skip to content

Commit 832903c

Browse files
committed
Optimize and make Modint safer
1 parent 93471f9 commit 832903c

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

content/number-theory/ModularArithmetic.h

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Author: Lukas Polacek
2+
* Author: Lukas Polacek, Joshua Andersson
33
* Date: 2009-09-28
44
* License: CC0
55
* Source: folklore
@@ -13,14 +13,15 @@
1313
const ll mod = 17; // change to something else
1414
struct Mod {
1515
ll x;
16-
Mod(ll xx) : x(xx) {}
17-
Mod operator+(Mod b) { return Mod((x + b.x) % mod); }
18-
Mod operator-(Mod b) { return Mod((x - b.x + mod) % mod); }
19-
Mod operator*(Mod b) { return Mod((x * b.x) % mod); }
16+
Mod(ll y) : Mod(y%mod+mod,0){}
17+
Mod(ll y,int) : x(y<mod?y:y-mod){}
18+
Mod operator+(Mod b) { return {x + b.x,0}; }
19+
Mod operator-(Mod b) { return {x - b.x + mod,0}; }
20+
Mod operator*(Mod b) { return {x * b.x % mod,0}; }
2021
Mod operator/(Mod b) { return *this * invert(b); }
2122
Mod invert(Mod a) {
22-
ll x, y, g = euclid(a.x, mod, x, y);
23-
assert(g == 1); return Mod((x + mod) % mod);
23+
ll x, y, g = euclid(a.x,mod,x,y);
24+
assert(g == 1); return x;
2425
}
2526
Mod operator^(ll e) {
2627
if (!e) return Mod(1);

0 commit comments

Comments
 (0)