operations modulo a prime number +, + =, -, - =, =, ==,! =,>, <,> =, <=, *, * =, /, / =
Please describe these operations that I need to do through operator overloading, if not difficult with examples.
operations modulo a prime number +, + =, -, - =, =, ==,! =,>, <,> =, <=, *, * =, /, / =
Please describe these operations that I need to do through operator overloading, if not difficult with examples.
Regarding the description and meaning of operations, you better consult with any book on higher algebra. This part of the question lies outside the scope of our site. You can start, for example, with Wikipedia .
Regarding data representation: to avoid problems associated with overflow (and modulo-2 arithmetic associated with this) to the extent of word size, it is best to use a longer type for operations that is guaranteed to contain the result of multiplication. You can use the canonical representation of a number to store the value.
We get something like this (C ++):
template<unsigned int p> class Residue { typedef unsigned int working_type; typedef signed int diff_type; typedef unsigned long operation_type; static_assert(sizeof(operation_type) >= 2 * sizeof(working_type)); static_assert(p > 1); working_type value; static working_type reduce(operation_type value) { operation_type residue = value % p; assert(0 <= residue && residue < p); // ΠΏΠΎΡΠΊΠΎΠ»ΡΠΊΡ residue < p, ΠΏΡΠΈΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ ΡΠΈΠΏΠΎΠ² Π±Π΅Π·ΠΎΠΏΠ°ΡΠ½ΠΎ return (working_type)residue; } static working_type reduce(diff_type value) { // Π½Π°ΠΌ Π½ΡΠΆΠ΅Π½ Π±ΠΎΠ»Π΅Π΅ ΡΠΈΡΠΎΠΊΠΈΠΉ ΡΠΈΠΏ, ΡΡΠΎΠ±Ρ ΡΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ Ρ `p` Π±ΡΠ»ΠΎ Π±Π΅Π·ΠΎΠΏΠ°ΡΠ½ΠΎ operation_type residue = value % p; operation_type residue = (remainder < 0) ? (remainder + p) : remainder; assert(0 <= residue && residue < p); // ΠΏΠΎΡΠΊΠΎΠ»ΡΠΊΡ residue < p, ΠΏΡΠΈΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ ΡΠΈΠΏΠΎΠ² Π±Π΅Π·ΠΎΠΏΠ°ΡΠ½ΠΎ return (working_type)residue; } Residue(operation_type v) : value(reduce(v)) { } public: Residue(working_type v) : value(reduce((operation_type)v)) { } Residue(diff_type v) : value(reduce(v)) { } Residue<p> operator + (const Residue<p>& other) { // Π·Π΄Π΅ΡΡ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ Π±ΡΡΡ ΠΏΠ΅ΡΠ΅ΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ auto sum = (operation_type)value + (operation_type)other.value; return Residue<p>(sum); } // ΠΎΡΡΠ°Π»ΡΠ½ΡΠ΅ ΠΌΠ΅ΡΠΎΠ΄Ρ Π±ΠΎΠ»Π΅Π΅-ΠΌΠ΅Π½Π΅Π΅ Π°Π½Π°Π»ΠΎΠ³ΠΈΡΠ½Ρ }; Watch out for possible overflow, it can spoil the result! Test for large p values.
Please note that if you need modulo 2^32 operations, you can simply use the usual arithmetic on uint32_t , the extra bits are discarded automatically. In addition to division, which will have to remember the Euclidean algorithm . (The sign type does not fit , the overflow on it has undefined behavior!) But this does not fit into your task, since the powers of two (the first one) are not prime numbers.
Source: https://ru.stackoverflow.com/questions/425655/
All Articles