Modular arithmetic
 
Betöltés...
Keresés...
Nincs egyezés
mod.cpp
Ugrás a fájl dokumentációjához.
1#include "mod.h"
2#include "gcdx.h"
3
4namespace bme {
5
6 int Mod::default_modulus = INITIAL_DEFAULT_MODULUS;
7 int Mod::print_mode = INITIAL_PRINT_MODE;
8
9 Mod Mod::add(const Mod& other)const {
10 if (is_invalid() || other.is_invalid() || mod != other.mod) {
11 return Mod(0, 0);
12 }
13 return Mod(val + other.val, mod);
14 }
15
16 Mod Mod::multiply(const Mod& other)const {
17 if (is_invalid() || other.is_invalid() || mod != other.mod) {
18 return Mod(0, 0);
19 }
20 return Mod(val * other.val, mod);
21
22 }
23
25 if (is_invalid()) { return Mod(0, 0); }
26 int a, b;
27 int d = gcdx(val, mod, a, b);
28 if (d > 1) {
29 return Mod(0, 0); //csak a modulushoz relatív prím elemekre számolható inverz
30 }
31
32 return Mod(a, mod);
33 }
34
35 Mod Mod::pow(int k)const {
36 if (is_invalid()) { return Mod(0, 0); }
37
38 //ha negatív a kitevő, akkor az inverzet emeljük (-k)-adik hatványra
39 if (k < 0) {
40 return inverse().pow(-k);
41 }
42
43 //ha k=0, akkor az érték 1
44 if (k == 0) { return Mod(1, mod); }
45
46 //ha k=1, akkor visszaadjuk saját magát
47 if (k == 1) { return *this; }
48
49 //ha a kitevő páros, akkor val^k=((val^{k/2})^2)
50 if (k % 2 == 0) {
51 Mod tmp = pow(k / 2);
52 return tmp * tmp;
53 }
54
55 //ha a kitevő páratlan, akkor val^k=((val^{(k-1)/2})^2*val)
56 Mod tmp = pow((k - 1) / 2);
57 return tmp * tmp * (*this);
58
59 }
60
61 ostream& operator<<(ostream& os, const Mod& M) {
62 if (!M.is_invalid()) {
64 os << "Mod(" << M.get_val() << "," << M.get_mod() << ")";
65 }
67 os << M.get_val();
68 }
69 }
70 else {
71 os << "INVALID";
72 }
73 return os;
74 }
75
76}
Definition mod.h:24
Mod multiply(const Mod &other) const
A szorzást megvalósító függvény.
Definition mod.cpp:16
int get_mod() const
Modulus lekérdezése.
Definition mod.h:107
Mod()
Default konstruktor.
Definition mod.h:58
Mod inverse() const
Az inverzet számoló függvény.
Definition mod.cpp:24
int get_val() const
Maradékosztály reprezentánsa.
Definition mod.h:92
bool is_invalid() const
Invalid objektum lekérdezése.
Definition mod.h:176
static int get_print_mode()
Kiírás módja.
Definition mod.h:155
Mod pow(int k) const
Hatványozás.
Definition mod.cpp:35
Mod add(const Mod &other) const
Az összeadást megvalósító függvény.
Definition mod.cpp:9
Legnagyobb közös osztó előállítása.
a mod n maradékosztályok gyűrűjét reprezentáló osztály
Definition gcdx.cpp:5
ostream & operator<<(ostream &os, const Mod &M)
Mod osztály kiírása a képernyőre.
Definition mod.cpp:61
int gcdx(int a, int b, int &x, int &y)
Legnagyobb közös osztó kiszámolása és előállítása.
Definition gcdx.cpp:7
const int NORMAL_PRINT_MODE
Definition mod.h:14
const int SHORT_PRINT_MODE
Definition mod.h:15
const int INITIAL_DEFAULT_MODULUS
a default modulus kezdeti értéke
Definition mod.h:13
const int INITIAL_PRINT_MODE
a print mode kezdeti értéke
Definition mod.h:17