Click on z_p.h to get source.
#include <iostream>
using namespace std;
class z_p {
static int modulus;
int residue; // range from 0 to modulus-1
public:
z_p() {residue = 0;}
z_p(int i) {residue = i % modulus;
if(residue < 0) residue += modulus;
}
z_p& operator/(const z_p& b) const
{return (*this) * b.recip();
}
z_p& operator*(const z_p& b) const
{z_p* val_ptr = new z_p;
val_ptr->residue = residue * b.residue % modulus;
return(*val_ptr);
}
z_p& recip(void) const;
friend int main(void);
};// end class z_p
z_p& z_p::recip(void) const
{ // The extended Euclidean algorithm
int x, y, q, sx, tx, sy, ty, temp;
x = modulus; y = residue;
//*** sx = 1; sy = 0;
tx = 0; ty = 1;
while(y != 0)
// always: gcd(modulus,residue) = gcd(x,y)
// sx*modulus + tx*residue = x
// sy*modulus + ty*residue = y
{q = x / y; // integer quotient
temp = y; y = x - q*y; x = temp;
//*** temp = sy; sy = sx - q*sy; sx = temp;
temp = ty; ty = tx - q*ty; tx = temp;
};
// now x = gcd(modulus,residue)
z_p* val_prt = new z_p(tx);
return(*val_prt);
}// end z_p::recip()
/**** test program */
int z_p::modulus = 7;
int main(void)
{cout << (z_p(2)/z_p(4)).residue << endl;
}// end main
/****/