Skip to content

Instantly share code, notes, and snippets.

@feltmax
Last active April 17, 2016 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feltmax/590ecbe3edffd0880c16af6574f975d2 to your computer and use it in GitHub Desktop.
Save feltmax/590ecbe3edffd0880c16af6574f975d2 to your computer and use it in GitHub Desktop.
modulo calculator
template <long long modulo>
class Modulo
{
private:
long long pow(long long q)
{
long long a=1;
long long y=x;
for(;q!=0;q>>=1)
{
if(q&1LL)a=(a*y)%mod;
y=(y*y)%mod;
}
return a;
}
long long inv(){return pow(mod-2);}
public:
long long mod = modulo;
unsigned long long x;
Modulo() : x(0) {}
Modulo(signed s) {while(s<0)s+=mod;x=s%mod;}
Modulo(signed long long s) {while(s<0)s+=mod;x=s%mod;}
operator int(){return (int) x;}
operator long long(){return (long long) x;}
void operator++(){(*this)+=1;}
void operator--(){(*this)-=1;}
Modulo &operator+=(Modulo q){if((x+=q.x)>=mod)x-=mod; return *this;}
Modulo &operator-=(Modulo q){if((x+=mod-q.x)>=mod)x-=mod; return *this;}
Modulo &operator*=(Modulo q){x=(unsigned long long)x*q.x%mod; return *this;}
Modulo &operator/=(Modulo q){x=(unsigned long long)x*q.inv()%mod; return *this;}
Modulo operator+(Modulo q){return Modulo(*this)+=q;}
Modulo operator-(Modulo q){return Modulo(*this)-=q;}
Modulo operator*(Modulo q){return Modulo(*this)*=q;}
Modulo operator/(Modulo q){return Modulo(*this)/=q;}
template<typename T> Modulo &operator+=(const T q){if((x+=q)>=mod)x-=mod; return *this;}
template<typename T> Modulo &operator-=(const T q){if((x+=mod-q)>=mod)x-=mod; return *this;}
template<typename T> Modulo &operator*=(const T q){x=(unsigned long long)x*q%mod; return *this;}
template<typename T> Modulo &operator/=(const T q){x=(unsigned long long)x*(Modulo(q)).inv()%mod; return *this;}
template<typename T> Modulo operator+(const T q){return Modulo(*this)+=q;}
template<typename T> Modulo operator-(const T q){return Modulo(*this)-=q;}
template<typename T> Modulo operator*(const T q){return Modulo(*this)*=q;}
template<typename T> Modulo operator/(const T q){return Modulo(*this)/=q;}
template<typename T> Modulo power(const T q){return Modulo(pow((long long)q));}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment