R
Ralf Goertz
Hi,
what would be the best design for a class that represents the ring of
integers modulo some other integer? The problem is it only makes senes
to add, substract etc two such numbers if the belong to the same ring,
i.e. they have the same modulus. First, I thought of something like
typedef unsigned long long Int;
template <Int m> class Zm {
Int v; //value mod m
Zm<m>
Zm<m> & operator+=(Zm<m> r) {
v=(v+r.v)%m;
return *this;
}
...
public:
Zm<m>(const Int _v=Int(0)):v(_v%m) {}
};
With this approach, elements from different rings cannot be used
together in arithmetical operations. But of course, all possible moduli
would need to be known at compile and for each modulus there would be a
separate class.
The other approach would be
class Zm {
Int m,v;
bool valid;
Zm & operator+=(Zm r) {
valid &= (r.valid && (m==r.m));
v=(v+r.v)%m;
return *this;
}
...
public:
Zm(const Int _m, const Int _v):m(_m),v(_v%m),valid(true) {}
};
But this is not very elegant. Is there some better approach? Maybe with
derived classes?
Ralf
what would be the best design for a class that represents the ring of
integers modulo some other integer? The problem is it only makes senes
to add, substract etc two such numbers if the belong to the same ring,
i.e. they have the same modulus. First, I thought of something like
typedef unsigned long long Int;
template <Int m> class Zm {
Int v; //value mod m
Zm<m>
Zm<m> & operator+=(Zm<m> r) {
v=(v+r.v)%m;
return *this;
}
...
public:
Zm<m>(const Int _v=Int(0)):v(_v%m) {}
};
With this approach, elements from different rings cannot be used
together in arithmetical operations. But of course, all possible moduli
would need to be known at compile and for each modulus there would be a
separate class.
The other approach would be
class Zm {
Int m,v;
bool valid;
Zm & operator+=(Zm r) {
valid &= (r.valid && (m==r.m));
v=(v+r.v)%m;
return *this;
}
...
public:
Zm(const Int _m, const Int _v):m(_m),v(_v%m),valid(true) {}
};
But this is not very elegant. Is there some better approach? Maybe with
derived classes?
Ralf