Modular numbers


arithm/Zp.H

template < int p, class T=int>  class Z
Integers modulo p. The number p should be a prime number, otherwise inversion and exponentiation may not be valid.
{
private:
  T rep;

public:
  Z(): rep(0) {}
  Z(int n): rep(n%p){}
  Z(char * s) { 
    Scl tmp(s); 
    tmp %= Scl(p); 
    rep=mpz_get_si(&tmp.z);
    rep%=p;
  }
  Z(const Z & z): rep(z.rep) {}

  Z&  operator= (const Z  z) {rep=z.rep; return *this;} 
  Z&  operator+=(const Z  z) {(rep += z.rep)%= p; return *this;}
  Z&  operator-=(const Z  z) {(rep -= z.rep)%= p; return *this;}
  Z&  operator*=(const Z  z) {(rep *= z.rep)%= p; return *this;}
  Z&  operator/=(const Z  z);
  bool   operator==(const Z  z) const {return ((rep-z.rep)%p)==0;}
  bool   operator!=(const Z  z) const {return !(*this==z);}

  friend inline 
  Z operator -(const Z a) {return Z(-a.rep);}
  friend inline 
  Z operator+(const Z  a, const  Z b){return (Z(a.rep+b.rep));}
  friend inline
  Z operator-(const Z  a, const  Z b){return (Z(a.rep-b.rep));}
  friend inline
  Z operator*(const Z  a, const  Z b){return (Z(a.rep*b.rep));}
  friend inline
  Z operator/(const Z  a, const  Z b){return (Z(a)/=b);}

   friend 
  ostream &  operator<<(ostream&  os, const Z  & z) {return (os << z.rep);}
  friend
  istream & operator>>(istream&  is, Z & z) {return (is >> z.rep);}

};