Created
August 4, 2015 09:55
-
-
Save GnsP/0f75de48d1449d0ee8f6 to your computer and use it in GitHub Desktop.
Modular Arithmatic Suit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef NETSEC_MODULAR_HPP_INCLUDED__ | |
| #define NETSEC_MODULAR_HPP_INCLUDED__ | |
| class modularInverseException: public std::exception{ | |
| virtual const char *what() const throw(){ | |
| return "Modular Inverse does not exist in this case."; | |
| } | |
| } modularInverseDoesNotExist; | |
| template<int Mod> | |
| class modular{ | |
| public: | |
| modular():n_(0){} | |
| modular(int n){ | |
| n = n % Mod; | |
| if(n<0) n = (n + Mod) % Mod; | |
| n_ = n; | |
| } | |
| modular(const modular &m):n_(m.n_){} | |
| inline void setval(int n){ | |
| n = n % Mod; | |
| if(n<0) n = (n + Mod) % Mod; | |
| n_ = n; | |
| } | |
| inline int getval() const { return n_; } | |
| inline int getmod() const { return Mod; } | |
| inline int operator()(int val){ | |
| setval(val); | |
| return n_; | |
| } | |
| inline int operator()() const{ | |
| return n_; | |
| } | |
| inline modular operator+(const modular &m) const{ | |
| int res = (n_ + m.n_) % Mod; | |
| res = (res + Mod)%Mod; | |
| return modular<Mod>(res); | |
| } | |
| inline void operator+=(const modular &m){ | |
| int res = (n_ + m.n_) % Mod; | |
| res += (res + Mod) % Mod; | |
| n_ = res; | |
| return; | |
| } | |
| inline modular operator-(const modular &m) const{ | |
| int res = (n_ - m.n_) % Mod; | |
| res = (res + Mod)%Mod; | |
| return modular<Mod>(res); | |
| } | |
| inline void operator-=(const modular &m){ | |
| int res = (n_ - m.n_) % Mod; | |
| res += (res + Mod) % Mod; | |
| n_ = res; | |
| return; | |
| } | |
| inline modular operator*(const modular &m) const{ | |
| int res = (n_ * m.n_) % Mod; | |
| res = (res + Mod)%Mod; | |
| return modular<Mod>(res); | |
| } | |
| inline void operator*=(const modular &m){ | |
| int res = (n_ * m.n_) % Mod; | |
| res += (res + Mod) % Mod; | |
| n_ = res; | |
| return; | |
| } | |
| inline void operator=(const modular &m){ | |
| n_ = m.n_; | |
| return; | |
| } | |
| inline bool operator==(const modular &m) const{ | |
| return n_ == m.n_; | |
| } | |
| inline void operator=(const int &m){ | |
| setval(m); | |
| return; | |
| } | |
| inline modular addInv() const{ | |
| int res = (Mod - n_) % Mod; | |
| return modular<Mod>(res); | |
| } | |
| inline modular multInv() const throw(){ | |
| int res = 0; | |
| for ( res=0; res < Mod; res++ ) | |
| if((n_ * res) % Mod == 1) | |
| return modular<Mod>(res); | |
| throw modularInverseDoesNotExist; | |
| } | |
| private: | |
| int n_; | |
| }; | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment